SMTP 使用 SSL 协议 端口 465 / 587
非 SSL 通道 端口 25
首先导入mail依赖包
javax.mail - mail - 1.4.7
final Properties props = new Properties();
props.put("mail.smtp.auth", email.getSmtpAuth());
props.put("mail.smtp.host", email.getSmtpService());
props.put("mail.transport.protocol", "smtp");
props.put("mail.debug", "false");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", email.getSmtpPort());
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
String userName = email.getFromMailAddress();
String password = email.getFromMailStmpPwd();
return new PasswordAuthentication(userName, password);}};
Session mailSession = Session.getInstance(props, authenticator);
MimeMessage message = new MimeMessage(mailSession);
String nickName = MimeUtility.encodeText(email.getNickname());
InternetAddress from = new InternetAddress(nickName + "<" + email.getFromMailAddress() + ">");
message.setFrom(from);
message.setSubject(email.getTitle());
if (email.getContentType().equals(MailContentTypeEnum.HTML.getValue())) {
message.setContent(email.getContent(), email.getContentType());
} else if (email.getContentType().equals(MailContentTypeEnum.TEXT.getValue())) {
message.setText(email.getContent());
}
List params = email.getList();
for (int i = 0; i < params.size(); i++) {
try {
InternetAddress to = new InternetAddress(params.get(i));
message.setRecipient(Message.RecipientType.TO, to);
Transport.send(message);
logger.info("send to " + params.get(i) + " success");
} catch (Exception e) {
logger.error(e.getMessage());
logger.info("send to " + params.get(i) + " unsuccess");
continue;
}
}
网友评论