我有一个通信应用程序,每个用户创建一个通信并将其发送给多个用户(平均发送给我们 2-30 个用户),每次发送我打开一个新线程并按照以下流程向用户组发送电子邮件(连接邮件服务器>发送>关闭连接)如下:
public class EmailService {
private String emailProtocol = null;
private String emailHostSMTP = null;
private String senderEmail = null;
private String senderUser = null;
private String senderPassword = null;
private String senderDisplayName = null;
private String emailPort = null;
public void initConfig() {
emailProtocol = GeneralServices.getConfig("emailProtocol");
emailHostSMTP = GeneralServices.getConfig("emailHostSMTP");
senderEmail = GeneralServices.getConfig("senderEmail");
senderUser = GeneralServices.getConfig("senderUser");
senderPassword = GeneralServices.getConfig("senderPassword");
senderDisplayName = GeneralServices.getConfig("senderDisplayName");
emailPort = GeneralServices.getConfig("emailPort");
if (StringUtils.isBlank(emailPort))
emailPort = "587";
}
public void setProps(Properties props) {
props.put("mail.transport.protocol", emailProtocol);
props.put("mail.smtp.host", emailHostSMTP);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", emailPort);
if (ConfigurationUtils.isEnableStartTlsInEmail())
props.put("mail.smtp.starttls.enable", "true");
if (ConfigurationUtils.isEnableDebugInEmail())
props.put("mail.debug", "true");
}
public void sendEmail(String toUser, String subject, String emailHtmlBody, String bannerPath) throws Exception {
try {
if (StringUtils.isBlank(toUser)) {
return;
}
List<String> toUsers = new ArrayList<String>(1);
toUsers.add(toUser);
sendEmail(toUsers, null, null, subject, emailHtmlBody, bannerPath);
} catch (Exception e) {
throw e;
}
}
public void sendEmail(String fromEmail, String fromDisplayName, List<String> toList, List<String> ccList,
String subject, String emailBody, String filePhysicalPath, String fileName, String fileContentType)
throws Exception {
Transport transport = null;
try {
initConfig();
MimeMultipart multipart = new MimeMultipart();
Authenticator authenticator = new SMTPAuthenticator();
MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
MimeBodyPart bodyPart = new MimeBodyPart();
String html = "";
Properties props = System.getProperties();
setProps(props);
sslSocketFactory.setTrustAllHosts(true);
props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
Session session = Session.getInstance(props, authenticator);
// session.setDebug(true);
emailBody = emailBody + "<br/><br/>مرسل بواسطة : " + fromDisplayName;
html = "<html><body style='text-align:right'> " + emailBody + " </body></html>";
bodyPart.setContent(html, "text/html; charset=UTF-8");
multipart.addBodyPart(bodyPart);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail, fromDisplayName));
message.setReplyTo(new Address[] { new InternetAddress(fromEmail) });
if (toList != null && toList.size() > 0) {
for (String to : toList) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
}
} else {
throw new Exception("List of users to send email to is empty");
}
if (ccList != null && ccList.size() > 0) {
for (String cc : ccList) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
}
}
// attach file
BodyPart mimeBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePhysicalPath);
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(MimeUtility.encodeText(fileName, "utf-8", "B"));
multipart.addBodyPart(mimeBodyPart);
// end of file attach
message.setSubject(subject, "UTF-8");
message.setContent(multipart);
message.setSentDate(new Date());
transport = session.getTransport(emailProtocol);
transport.connect(senderEmail, senderPassword);
transport.sendMessage(message, message.getAllRecipients());
} catch (Exception ex) {
throw ex;
} finally {
if (transport != null)
transport.close();
}
}
public void sendEmail(List<String> toList, List<String> ccList, List<String> bccList, String subject,
String emailHtmlBody, String bannerPath) throws Exception {
if ((toList == null || toList.size() == 0) && (ccList == null || ccList.size() == 0)
&& (bccList == null || bccList.size() == 0)) {
return;
}
Transport transport = null;
try {
initConfig();
MimeMultipart multipart = new MimeMultipart();
Authenticator authenticator = new SMTPAuthenticator();
MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
MimeBodyPart bodyPart = new MimeBodyPart();
String html = "";
Properties props = System.getProperties();
setProps(props);
sslSocketFactory.setTrustAllHosts(true);
props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
Session session = Session.getInstance(props, authenticator);
html = "<html><body> " + emailHtmlBody + " </body></html>";
bodyPart.setContent(html, "text/html; charset=UTF-8");
multipart.addBodyPart(bodyPart);
// add banner path
bodyPart = new MimeBodyPart();
DataSource ds = new FileDataSource(bannerPath);
bodyPart.setDataHandler(new DataHandler(ds));
bodyPart.setHeader("Content-ID", "<MOAMALAT_LOGO>");
multipart.addBodyPart(bodyPart);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail, senderDisplayName));
message.setReplyTo(new Address[] { new InternetAddress(senderEmail) });
if (toList != null && toList.size() > 0) {
for (String email : toList)
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
}
if (ccList != null && ccList.size() > 0) {
for (String email : ccList)
message.addRecipient(Message.RecipientType.CC, new InternetAddress(email));
}
if (bccList != null && bccList.size() > 0) {
for (String email : bccList)
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email));
}
message.setSubject(subject, "UTF-8");
message.setContent(multipart);
message.setSentDate(new Date());
transport = session.getTransport(emailProtocol);
transport.connect(senderEmail, senderPassword);
transport.sendMessage(message, message.getAllRecipients());
} catch (Exception ex) {
throw ex;
} finally {
if (transport != null)
transport.close();
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = senderUser;
String password = senderPassword;
return new PasswordAuthentication(username, password);
}
}
}
有时我会得到错误:
com.sun.mail.smtp.SMTPSendFailedException: 421 4.4.2 Message submission rate for this client has exceeded the configured limit
但在与 Exchange Server 管理员审查后,他说我没有发送超过限制的电子邮件。
有时我也会收到错误:
java.net.SocketException: Connection reset
有时我也会得到:
javax.mail.MessagingException: Can't send command to SMTP host,Caused by: java.net.SocketException: Connection closed by remote host
我读到有些人将传输对象设为静态并仅与交换服务器建立一次连接然后重新使用它,这是否有助于解决问题,连接将打开多长时间?
我还想到了一种解决方案,将电子邮件详细信息保存在数据库表中,并制作一个作业类以定期批量发送电子邮件。
最佳答案
我编辑了您第二次声明的 sendEmail 方法(如下所示)。如果您喜欢,请将相同的技术应用于其他 sendEmail 方法。
作为解决方案,我将 sendMessage 部分抓取到 cc 列表的 for 循环中。因此,对于每个“收件人”电子邮件和每个相应的“抄送”电子邮件,将发送电子邮件。抄送列表的缺失也必须由您评估。代码可能无法编译,但您应该明白这一点。
public void sendEmail(String fromEmail, String fromDisplayName, List<String> toList, List<String> ccList,
String subject, String emailBody, String filePhysicalPath, String fileName, String fileContentType)
throws Exception {
Transport transport = null;
try {
initConfig();
MimeMultipart multipart = new MimeMultipart();
Authenticator authenticator = new SMTPAuthenticator();
MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
MimeBodyPart bodyPart = new MimeBodyPart();
String html = "";
Properties props = System.getProperties();
setProps(props);
sslSocketFactory.setTrustAllHosts(true);
props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
Session session = Session.getInstance(props, authenticator);
// session.setDebug(true);
emailBody = emailBody + "<br/><br/>مرسل بواسطة : " + fromDisplayName;
html = "<html><body style='text-align:right'> " + emailBody + " </body></html>";
bodyPart.setContent(html, "text/html; charset=UTF-8");
multipart.addBodyPart(bodyPart);
MimeMessage message = new MimeMessage(session);
// attach file
BodyPart mimeBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePhysicalPath);
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(MimeUtility.encodeText(fileName, "utf-8", "B"));
multipart.addBodyPart(mimeBodyPart);
// end of file attach
message.setSubject(subject, "UTF-8");
message.setContent(multipart);
message.setFrom(new InternetAddress(senderEmail, fromDisplayName));
message.setReplyTo(new Address[] { new InternetAddress(fromEmail) });
transport = session.getTransport(emailProtocol);
transport.connect(senderEmail, senderPassword);
if (toList != null && toList.size() > 0) {
for (String to : toList) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
if (ccList != null && ccList.size() > 0) {
for (String cc : ccList) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
message.setSentDate(new Date());
transport.sendMessage(message, message.getAllRecipients());
}
}
}
} else {
throw new Exception("List of users to send email to is empty");
}
} catch (Exception ex) {
throw ex;
} finally {
if (transport != null)
transport.close();
}
}
关于java - 无法在短时间内发送太多电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43466897/