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

JavaMail 與 Apache Commons Email 郵件發送完整指南

     編輯:Java 相關知識

郵件發送基礎概念

電子郵件由多個核心要素組成:收件人、寄件人、主旨、內容(含附件)等。Java 應用程式通常透過 SMTP 伺服器(如 smtp.gmail.com、smtp.qq.com)發送郵件,需經過身分驗證後才能發送。

兩大主流方案比較

特性JavaMail (Jakarta Mail)Apache Commons Email
依賴mail.jarmail.jar + commons-email.jar
API 風格底層、細粒度控制高層封裝、鏈式呼叫
學習曲線較陡峭平緩
適用場景需精細控制 MIME、自定義 Header一般業務郵件、快速開發

JavaMail 完整實作範例

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class JavaMailSender {

    public static void send(String host, String user, String password,
                            String from, String to, String subject, String htmlContent) throws MessagingException {
        
        // 1. 設定 SMTP 參數
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.starttls.enable", "true"); // TLS 加密

        // 2. 建立 Session(方式一:手動連線)
        Session session = Session.getInstance(props);
        session.setDebug(true); // 開啟除錯輸出

        // 3. 建立郵件訊息
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject, "UTF-8");
        message.setContent(htmlContent, "text/html;charset=UTF-8");

        // 4. 發送
        Transport transport = session.getTransport("smtp");
        transport.connect(user, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    // 方式二:使用 Authenticator 自動驗證(適合連線池)
    public static void sendWithAuth(Session session, Message message) throws MessagingException {
        Transport.send(message);
    }
}

Apache Commons Email 簡化寫法

org.apache.commons.mail.*;

public class CommonsEmailSender {
    private final String host;
    private final String user;
    private final String password;
    private final String fromEmail;
    private final String fromName;

    public CommonsEmailSender(String host, String user, String password, String fromEmail, String fromName) {
        this.host = host;
        this.user = user;
        this.password = password;
        this.fromEmail = fromEmail;
        this.fromName = fromName;
    }

    /** 純文字郵件 */
    public void sendSimple(String to, String toName, String subject, String text) throws EmailException {
        SimpleEmail email = new SimpleEmail();
        configCommon(email);
        email.addTo(to, toName);
        email.setSubject(subject);
        email.setMsg(text);
        email.send();
    }

    /** HTML 郵件 */
    public void sendHtml(String to, String toName, String subject, String html) throws EmailException {
        HtmlEmail email = new HtmlEmail();
        configCommon(email);
        email.addTo(to, toName);
        email.setSubject(subject);
        email.setHtmlMsg(html);
        email.setTextMsg("您的郵件用戶端不支援 HTML,請查看網頁版。");
        email.send();
    }

    /** 含附件郵件 */
    public void sendWithAttachment(String to, String toName, String subject, String html, String filePath, String fileName) throws EmailException {
        MultiPartEmail email = new MultiPartEmail();
        configCommon(email);
        email.addTo(to, toName);
        email.setSubject(subject);
        email.setHtmlMsg(html);
        
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(filePath);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("附件說明");
        attachment.setName(MimeUtility.encodeText(fileName)); // 解決中文檔名亂碼
        email.attach(attachment);
        email.send();
    }

    private void configCommon(Email email) {
        email.setHostName(host);
        email.setAuthentication(user, password);
        email.setCharset("UTF-8");
        email.setFrom(fromEmail, fromName);
        email.setSSLOnConnect(true); // 若使用 465 埠
        // email.setStartTLSEnabled(true); // 若使用 587 埠
    }
}

常見問題與最佳實踐

  • 連線超時:檢查防火牆、SMTP 埠號(465 SSL / 587 TLS)、網路連通性。
  • 驗證失敗:啟用「低安全性應用程式存取」或使用應用程式專用密碼(Gmail、Outlook 等)。
  • 中文亂碼:統一使用 UTF-8,附件檔名需 MimeUtility.encodeText() 編碼。
  • 大量發送:建議使用連線池 Session.getInstance(props, authenticator) 並重用 Transport 物件。
  • 測試工具:開發階段可使用 MockMock 或 Mailtrap 攔截測試郵件。

Maven 依賴座標

<!-- JavaMail (Jakarta Mail) -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>2.0.1</version>
</dependency>

<!-- Apache Commons Email -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-email</artifactId>
    <version>1.5</version>
</dependency>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved