javax.mail.Authenticator。public class MailSenderInfo {
private String mailServerHost, mailServerPort = "25";
private String fromAddress, toAddress, userName, password;
private boolean validate = false;
private String subject, content;
private String[] attachFileNames;
public Properties getProperties() {
Properties p = new Properties();
p.put("mail.smtp.host", mailServerHost);
p.put("mail.smtp.port", mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
// 省略 Getter/Setter
}
public class SimpleMailSender {
// 文本郵件
public boolean sendTextMail(MailSenderInfo info) {
Session session = createSession(info);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(info.getFromAddress()));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(info.getToAddress()));
msg.setSubject(info.getSubject());
msg.setSentDate(new Date());
msg.setText(info.getContent());
Transport.send(msg);
return true;
} catch (MessagingException e) { e.printStackTrace(); return false; }
}
// HTML 郵件
public static boolean sendHtmlMail(MailSenderInfo info) {
Session session = createSession(info);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(info.getFromAddress()));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(info.getToAddress()));
msg.setSubject(info.getSubject());
msg.setSentDate(new Date());
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(info.getContent(), "text/html; charset=utf-8");
mp.addBodyPart(htmlPart);
msg.setContent(mp);
Transport.send(msg);
return true;
} catch (MessagingException e) { e.printStackTrace(); return false; }
}
private static Session createSession(MailSenderInfo info) {
Authenticator auth = info.isValidate() ? new MyAuthenticator(info.getUserName(), info.getPassword()) : null;
return Session.getDefaultInstance(info.getProperties(), auth);
}
}
public class MyAuthenticator extends Authenticator {
private final String userName, password;
public MyAuthenticator(String userName, String password) {
this.userName = userName; this.password = password;
}
@Override protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}
MailSenderInfo info = new MailSenderInfo();
info.setMailServerHost("smtp.163.com");
info.setMailServerPort("465"); // SSL 端口
info.setValidate(true);
info.setUserName("your@163.com");
info.setPassword("auth_code"); // 授權碼,非登錄密碼
info.setFromAddress("your@163.com");
info.setToAddress("target@qq.com");
info.setSubject("測試標題");
info.setContent("<h1 style='color:red'>HTML 內容</h1>");
new SimpleMailSender().sendHtmlMail(info);
mail.smtp.ssl.enable=true 或 mail.smtp.starttls.enable=true;Multipart 中再添加 MimeBodyPart 並 attachFile()。將三個類打包為 mail-util.jar,未來專案引入即用,告別重複造輪子。