首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

JavaMail 發送郵件完整實戰:文本/HTML/附件/SSL 全覆蓋

     編輯:Java 相關知識

架構設計:三層解耦

  1. MailSenderInfo:郵件元數據載體(主機、認證、收發件人、主題、正文、附件);
  2. SimpleMailSender:發送引擎,封裝 Session 創建、MimeMessage 組裝、Transport 發送;
  3. MyAuthenticator:認證策略,實現 javax.mail.Authenticator。

核心代碼精要

1. 郵件信息封裝

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
}

2. 發送引擎:文本 + HTML 双模式

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);
    }
}

3. 認證器

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);

避坑指南(血淚總結)

  • 新註冊郵箱無法發送:需養號一段時間,或使用成熟賬號;
  • SMTP 主機與發件人域名必須一致:用 smtp.163.com 發件人必須是 @163.com;
  • 授權碼 ≠ 登錄密碼:開啟 SMTP 服務後獲取專用授權碼;
  • SSL/TLS 端口:465 (SSL) / 587 (STARTTLS),對應配置 mail.smtp.ssl.enable=true 或 mail.smtp.starttls.enable=true;
  • 附件發送:在 Multipart 中再添加 MimeBodyPart 並 attachFile()。

將三個類打包為 mail-util.jar,未來專案引入即用,告別重複造輪子。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved