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

Java 郵件發送完整實作:支援附件與群發

     編輯:Java 相關知識

核心發送邏輯

以下封裝了一個可直接用於生產環境的 MailSender 類別,支援單發、群發、HTML 內容與附件編碼處理:

public class MailSender {
    // ... 屬性定義(host, fromAddr, username, password 等) ...

    /** 發送單一郵件 */
    public void sendMail() throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.host", getHost());
        props.put("mail.smtp.auth", "true");
        Session session = Session.getInstance(props, null);
        
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(getFromAddr()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(getToAddr()));
        message.setSubject(getTitle());
        
        // 建立多部分內容:HTML 正文 + 附件
        Multipart multipart = new MimeMultipart();
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(getSendtext(), "text/html;charset=GBK");
        multipart.addBodyPart(contentPart);
        
        if (getAttachPath() != null && getAttachName() != null) {
            BodyPart attachmentPart = new MimeBodyPart();
            DataSource source = new FileDataSource(getAttachPath());
            attachmentPart.setDataHandler(new DataHandler(source));
            // 附件檔名編碼,解決中文亂碼
            BASE64Encoder enc = new BASE64Encoder();
            attachmentPart.setFileName("=?GBK?B?" + enc.encode(getAttachName().getBytes()) + "?=");
            multipart.addBodyPart(attachmentPart);
        }
        
        message.setContent(multipart);
        message.saveChanges();
        
        Transport transport = session.getTransport("smtp");
        transport.connect(getHost(), getUsername(), getPassword());
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /** 群發郵件 */
    public void sendMails() throws Exception {
        // 類似 sendMail,差異在於使用 setRecipients 設定多個收件人
        InternetAddress[] address = new InternetAddress[getMutliTo().length];
        for (int i = 0; i < getMutliTo().length; i++) {
            address[i] = new InternetAddress(getMutliTo()[i]);
        }
        message.setRecipients(Message.RecipientType.TO, address);
        // 其餘邏輯同 sendMail
    }
    
    // Getter/Setter 略...
}

設定檔範例

# Email 設定
host=smtp.163.com
username=your_account
password=your_password
fromadd=your_account@163.com

關鍵技術點解析

  • Session.getInstance vs getDefaultInstance:前者每次建立新 Session,適合多執行緒環境;後者回傳共享預設實例。
  • MimeMultipart:實現混合內容(文字+附件)的標準方式。
  • 附件檔名編碼:使用 BASE64Encoder 搭配 MIME 編碼格式 =?charset?B?encoded?=,確保中文附件名在各郵件客戶端正常顯示。
  • 資源釋放:務必在 finally 區塊關閉 Transport 連線,避免連線洩漏。

進階建議

  • 生產環境建議使用連線池管理 SMTP 連線。
  • 整合 Spring 的 JavaMailSender 可進一步簡化配置與異常處理。
  • 大量郵件發送時,考慮使用非同步佇列(如 RabbitMQ)削峰填谷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved