使用sina的邮件服务器发送,原来的
mail.smtp.server=smtp.sina.com
mail.smtp.port=25
后来切换成阿里云服务器之后,发现本来可以发送的邮件发送失败并且报错如下:
java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.sina.com, port: 25;
INFO | jvm 1 | main | 2018/10/11 17:02:01.278 | nested exception is:
INFO | jvm 1 | main | 2018/10/11 17:02:01.278 | java.net.ConnectException: Connection timed out (Connection timed out)
通过调查之后才发现,原来阿里云服务器25端口不能出,被禁了。只能使用Sina的加密端口。更高配置如下:
mail.smtp.server=smtp.sina.com
mail.smtp.port=465
使用加密端口,需要注意的是必须要带上特定的参数才行。
pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
否则回报错如下:
INFO | jvm 1 | main | 2018/10/11 17:32:57.548 | Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.sina.com, port: 465, response: -1
INFO | jvm 1 | main | 2018/10/11 17:32:57.548 | at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1922) ~[mail-1.4.4.jar:1.4.4]
INFO | jvm 1 | main | 2018/10/11 17:32:57.548 |
上面是说明出现问题的原因和解决办法。下面贴出发送部分邮件部分主要代码:
import ilism.mail.MailAuthenticator;
import ilism.mail.MailSender;
import ilism.mail.MailSenderInfo;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.hsqldb.lib.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public static void main(String[] args){
//initialize
MailSenderInfo info = new MailSenderInfo();
info.setMailServerHost(configurationService.getConfiguration().getString("mail.smtp.server"));//发件箱服务器
info.setMailServerPort(configurationService.getConfiguration().getString("mail.smtp.port"));//发件箱服务器端口
info.setValidate(true);
info.setFromAddress(configurationService.getConfiguration().getString("mail.from"));//from address
info.setUserName(configurationService.getConfiguration().getString("mail.smtp.user"));//用户名
info.setPassword(configurationService.getConfiguration().getString("mail.smtp.password"));//密码
try
{
//send email
info.setSubject(current.getTitle());
info.setContent(current.getContent());
info.setToAddress(current.getEmail());
if (current.getFileAttachment() != null && !StringUtil.isEmpty(current.getFileAttachment()))
{
//带附件
info.setAttachFileNames(new String[]
{ current.getFileAttachment() });
this.sendHtmlMailWithFileCopy(info);
}
else
{
//html
info.setAttachFileNames(null);
this.sendHtmlMailCopy(info);
}
//标记已发送成功
current.setHasSendFlag(Boolean.TRUE);
modelService.save(current);
Thread.sleep(2000);
}
catch (final Exception e)
{
if (e instanceof javax.mail.MessagingException)
{
//不能连smtp的等到下一次处理
Logger.getLogger(e.getClass()).error("wait for next email send action!", e);
}
else
{
throw e;
}
}
}
//html发送
public boolean sendHtmlMailCopy(MailSenderInfo mailInfo) {
MailAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
if (mailInfo.isValidate()) {
authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
try {
Message mailMessage = new MimeMessage(sendMailSession);
Address from = new InternetAddress(mailInfo.getFromAddress());
mailMessage.setFrom(from);
String[] var9;
int var8 = (var9 = mailInfo.getToAddress().split(";")).length;
for(int var7 = 0; var7 < var8; ++var7) {
String one = var9[var7];
mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(one));
}
mailMessage.setSubject(mailInfo.getSubject());
mailMessage.setSentDate(new Date());
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
mailMessage.setContent(mainPart);
Transport transport = sendMailSession.getTransport("smtp");
transport.connect(mailInfo.getMailServerHost(), mailInfo.getUserName(), mailInfo.getPassword());
transport.sendMessage(mailMessage, mailMessage.getRecipients(Message.RecipientType.TO));
transport.close();
return true;
} catch (MessagingException var10) {
Logger.getLogger(var10.getClass()).error("", var10);
throw new RuntimeException(var10);
}
}
//带附件发送
public boolean sendHtmlMailWithFileCopy(MailSenderInfo mailInfo) {
MailAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
if (mailInfo.isValidate()) {
authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
try {
Message mailMessage = new MimeMessage(sendMailSession);
Address from = new InternetAddress(mailInfo.getFromAddress());
mailMessage.setFrom(from);
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO, to);
mailMessage.setSubject(mailInfo.getSubject());
mailMessage.setSentDate(new Date());
Multipart mainPart = new MimeMultipart("related");
BodyPart html = new MimeBodyPart();
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
String[] var12;
int var11 = (var12 = mailInfo.getAttachFileNames()).length;
for(int var10 = 0; var10 < var11; ++var10) {
String file = var12[var10];
html = new MimeBodyPart();
DataSource fileDataSource = new FileDataSource(file);
html.setDataHandler(new DataHandler(fileDataSource));
html.setHeader("Content-ID", (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date()));
html.setHeader("Content-Disposition", "attachment;filename=" + getFileName(file));
mainPart.addBodyPart(html);
}
mailMessage.setContent(mainPart);
Transport.send(mailMessage);
return true;
} catch (MessagingException var14) {
Logger.getLogger(var14.getClass()).error("", var14);
throw new RuntimeException(var14);
}
}
private static String getFileName(String content) {
content = content.replace('\\', '/');
return content.substring(content.lastIndexOf(47) + 1);
}
}