我正在使用Java Mail(1.4.7)发送电子邮件。我计划创建一个SMTP连接并重新使用它(通过保持活动状态)。我正在使用的代码如下所述。当我按预期运行程序时,我在日志中看到“已发送电子邮件”,但邮件未送达。此外,日志没有错误。如果我杀了程序(在eclipse上循环运行),邮件就会被传递。
或者,如果我在每个发送请求中关闭连接(通过调用smtpTransport.close()),邮件将被传递(不会终止程序)。但这与为每个邮件发送请求创建新的SMTP连接一样好。
只是想知道,如果这可能是SMTP服务器问题?
private Session smtpSession;
private Transport smtpTransport;
public synchronized void send(String toAddress, String ccAddress, String bccAddress, String emailSubject,
String emailContent) throws MessagingException {
// check if we need to create a new connection
establishSmtpConnection();
Message message = new MimeMessage(smtpSession);
// set From: header field of the header.
message.setFrom(new InternetAddress(smtpFromAddress));
// set to recepients
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress, true));
// set cc recepients
if (ccAddress != null && !ccAddress.trim().equals("")) {
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddress, true));
}
// set bcc recepients
if (bccAddress != null && !bccAddress.trim().equals("")) {
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccAddress, true));
}
// set Subject: header field
message.setSubject(emailSubject);
// set the actual message
Multipart multiPart = new MimeMultipart("alternative");
// create the HTML message
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(emailContent, "text/html; charset=utf-8");
multiPart.addBodyPart(htmlPart);
message.setContent(multiPart);
Address[] allRecipients = message.getAllRecipients();
LOGGER.info("Going to send email. message:{}, allRecipients:{}", message, allRecipients);
message.saveChanges();
// Send message
smtpTransport.sendMessage(message, allRecipients);
// ****** MAILS ARE DELIVERED INSTANTLY IF THE FOLLOWING IS UNCOMMENTED ************
// smtpTransport.close();
LOGGER.info("Email has been sent");
}
/**
* Establishes SMTP connection if not connected already.
* @throws MessagingException
*/
private synchronized void establishSmtpConnection() throws MessagingException {
if (smtpTransport != null && smtpTransport.isConnected()) {
LOGGER.debug("Will re-use exisitng SMTP connection..");
return;
} else {
synchronized (MailUtil.class) { // double null check
if (smtpTransport == null || !smtpTransport.isConnected()) {
// establish SMTP connection
LOGGER.info(
"Going to create a new SMTP connection. smtpHost:" + smtpHost + ", smtpPort:" + smtpPort);
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", smtpHost);
mailProps.put("mail.smtp.port", smtpPort);
smtpSession= Session.getInstance(mailProps, null);
smtpSession.setDebug(debug);
smtpTransport = smtpSession.getTransport("smtp");
LOGGER.info("Connecting to SMTP server...");
smtpTransport.connect();
LOGGER.info("Successfully connected to SMTP server...");
}
}
}
}