基於 JavaMail API 實現郵件發送是企業級應用的剛需。本文提供一套完整、可復用的郵件發送架構,覆蓋屬性封裝、認證器、發送工具類、異常處理及實戰測試。
public class MailSendProper {
private String host; // SMTP 服務器
private String port; // 端口
private String sendAddress; // 發件人
private String receiveAddress; // 收件人
private String username; // 登錄用戶名
private String password; // 登錄密碼/授權碼
private boolean validate = true; // 是否認證
private String subject; // 主題
private String content; // 正文
// Getter/Setter 省略...
public Properties getProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", validate ? "true" : "false");
return props;
}
}
public class EmailMessage {
private String title;
private String context;
private String toEmail;
// 構造器、Getter/Setter 省略...
}
public class MailAttorney extends Authenticator {
private final String username;
private final String password;
public MailAttorney(String username, String password) {
this.username = username;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
public class MailSend {
/** 低層發送邏輯 */
public static boolean mailTest(MailSendProper config) {
Authenticator auth = config.isValidate()
? new MailAttorney(config.getUsername(), config.getPassword())
: null;
Session session = Session.getInstance(config.getProperties(), auth);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(config.getSendAddress()));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(config.getReceiveAddress()));
message.setSubject(config.getSubject());
message.setSentDate(new Date());
message.setText(config.getContent()); // 純文本;HTML 用 setContent(content, "text/html;charset=utf-8")
Transport.send(message);
return true;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
}
/** 業務層發送入口 */
public static boolean sendEmail(EmailMessage msg) {
MailSendProper config = new MailSendProper();
config.setHost("smtp.126.com"); // 根據郵箱服務商修改
config.setPort("25"); // SSL 可用 465/587
config.setValidate(true);
config.setUsername("your_email@126.com");
config.setPassword("your_auth_code"); // 注意:這裡是授權碼,非登錄密碼
config.setSendAddress("your_email@126.com");
config.setReceiveAddress(msg.getToEmail());
config.setSubject(msg.getTitle());
config.setContent(msg.getContext());
return mailTest(config);
}
}
| 郵箱 | SMTP 服務器 | 端口 | 備註 |
|---|---|---|---|
| 126/163 | smtp.126.com | 25/465/587 | 需開啟 SMTP 服務,獲取授權碼 |
| smtp.qq.com | 25/465/587 | 需開啟 SMTP,獲取授權碼 | |
| Gmail | smtp.gmail.com | 587 | 需開啟「低安全性應用」或應用專用密碼 |
public static void main(String[] args) {
EmailMessage msg = new EmailMessage();
String code = String.valueOf(Math.random()).substring(3, 9); // 6位驗證碼
msg.setTitle("郵箱驗證碼");
msg.setContext("尊敬的用戶,您的驗證碼為:" + code + ",請勿泄露。");
msg.setToEmail("target@qq.com");
boolean success = MailSend.sendEmail(msg);
System.out.println(success ? "發送成功" : "發送失敗");
}
@Async 或線程池,避免阻塞主線程mail.smtp.connectionpool 復用連接spring.mail.*,注入 JavaMailSender 簡化代碼props.put("mail.smtp.ssl.enable", "true")