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

JavaMail 發送郵件全攻略:支援多附件、HTML 正文與中文主旨編碼

     編輯:Java 相關知識

發送郵件是企業級應用的高頻需求。本例封裝了一個功能完備的 Mail 工具類,支援 SMTP 認證、多附件、HTML/純文字正文、中文主旨編碼(GB2312),並提供流暢的 Setter 鏈式調用風格,可直接整合專案使用。

核心類設計亮點

  • 靈活配置:提供無參建構子 + Setter 方法,也支援全參數建構子,適應不同調用場景。
  • 中文主旨編碼:transferChinese() 使用 MimeUtility.encodeText() 依 RFC 2047 標準進行 Base64 編碼(=?GB2312?B?...?=),解決郵件客戶端顯示亂碼問題。
  • 多附件支援:Vector 維護附件路徑列表,attachfile() 疊加,發送時迴圈構建 MimeBodyPart + FileDataSource 加入 MimeMultipart。
  • SMTP 認證:props.put("mail.smtp.auth", "true") + 自定義 Authenticator 實作 getPasswordAuthentication()。

發送核心流程

public boolean sendMail() {
    // 1. 建立 Session (含認證)
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    // 2. 構建 MimeMessage
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    msg.setSubject(transferChinese(subject)); // 中文編碼

    // 3. 構建 Multipart 容器
    Multipart mp = new MimeMultipart();

    // 3.1 加入正文
    MimeBodyPart mbpContent = new MimeBodyPart();
    mbpContent.setText(content); // 或 setContent(html, "text/html;charset=UTF-8")
    mp.addBodyPart(mbpContent);

    // 3.2 加入附件
    for (String fname : file) {
        MimeBodyPart mbpFile = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(fname);
        mbpFile.setDataHandler(new DataHandler(fds));
        mbpFile.setFileName(MimeUtility.encodeText(fds.getName())); // 附件名也需編碼
        mp.addBodyPart(mbpFile);
    }

    // 4. 發送
    msg.setContent(mp);
    msg.setSentDate(new Date());
    Transport.send(msg);
    return true;
}

實戰避坑指南

  • 編碼統一:正文建議用 setContent(html, "text/html;charset=UTF-8"),附件檔名同樣需 MimeUtility.encodeText(),避免中文附件名亂碼。
  • SSL/TLS:現代 SMTP 多要求加密(465 隱性 SSL / 587 STARTTLS)。需額外設定:props.put("mail.smtp.ssl.enable", "true") 或 props.put("mail.smtp.starttls.enable", "true"),並對應連接埠。
  • 大附件/超時:設定 mail.smtp.connectiontimeout, mail.smtp.timeout;超大附件考慮分卷或雲存儲連結替代。
  • 發送失敗重試:生產環境建議引入訊息佇列(RabbitMQ/Kafka)實現異步重試與削峰填谷。

測試主程式

public static void main(String[] args) {
    Mail sendmail = new Mail();
    sendmail.setHost("smtp.sohu.com");
    sendmail.setUserName("your_account");
    sendmail.setPassWord("your_password");
    sendmail.setTo("recipient@example.com");
    sendmail.setFrom("sender@sohu.com");
    sendmail.setSubject("測試郵件 - 中文主旨");
    sendmail.setContent("這是一封帶附件的測試郵件!");
    sendmail.attachfile("c:\\test.txt");
    sendmail.attachfile("DND.jar");
    sendmail.sendMail();
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved