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

JavaMail 發送郵件完整實戰:文本、HTML、附件、SSL 全支援

     編輯:Java 程式設計入門

前置準備

  • 引入 javax.mail:mail:1.4.7 或 Spring Boot spring-boot-starter-mail
  • 開啟郵箱 SMTP 服務並獲取授權碼(非登錄密碼),如 163、QQ、Gmail 等

核心架構三層設計

  1. MailSenderInfo:資料傳輸物件,封裝主機、端口、認證、發件人、收件人、主題、內容、附件路徑
  2. SimpleMailSender:發送引擎,支援純文本、HTML、附件、內嵌圖片
  3. MyAuthenticator:實現 Authenticator,提供用戶名/密碼認證

關鍵代碼實現

1. 郵件信息封裝

public class MailSenderInfo {
    private String mailServerHost = "smtp.163.com";
    private String mailServerPort = "25"; // SSL 用 465/587
    private String fromAddress;
    private String toAddress;
    private String userName;
    private String password;
    private boolean validate = true;
    private String subject;
    private String 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");
        // SSL 配置
        // p.put("mail.smtp.ssl.enable", "true");
        // p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        return p;
    }
    // getter/setter 略
}

2. 發送引擎核心

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 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());
            
            MimeMultipart multipart = new MimeMultipart();
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(info.getContent(), "text/html; charset=utf-8");
            multipart.addBodyPart(htmlPart);
            
            msg.setContent(multipart);
            Transport.send(msg);
            return true;
        } catch (MessagingException e) { e.printStackTrace(); return false; }
    }

    // 發送帶附件
    public boolean sendAttachMail(MailSenderInfo info) {
        Session session = createSession(info);
        try {
            MimeMessage msg = new MimeMessage(session);
            // ... 設置發件人、收件人、主題、時間同前
            
            MimeMultipart multipart = new MimeMultipart();
            
            // 文本/HTML 部分
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setContent(info.getContent(), "text/html; charset=utf-8");
            multipart.addBodyPart(textPart);
            
            // 附件部分
            if (info.getAttachFileNames() != null) {
                for (String filePath : info.getAttachFileNames()) {
                    MimeBodyPart attachPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(filePath);
                    attachPart.setDataHandler(new DataHandler(source));
                    // 解決中文附件名亂碼
                    attachPart.setFileName(MimeUtility.encodeText(new File(filePath).getName()));
                    multipart.addBodyPart(attachPart);
                }
            }
            
            msg.setContent(multipart);
            Transport.send(msg);
            return true;
        } catch (Exception e) { e.printStackTrace(); return false; }
    }

    private Session createSession(MailSenderInfo info) {
        Authenticator auth = null;
        if (info.isValidate()) {
            auth = new MyAuthenticator(info.getUserName(), info.getPassword());
        }
        return Session.getInstance(info.getProperties(), auth);
    }
}

3. 認證器

public class MyAuthenticator extends Authenticator {
    private String username, password;
    public MyAuthenticator(String username, String password) {
        this.username = username;
        this.password = password;
    }
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
}

調用示例

public class MailTest {
    public static void main(String[] args) {
        MailSenderInfo info = new MailSenderInfo();
        info.setMailServerHost("smtp.qq.com");
        info.setMailServerPort("465"); // SSL
        info.setValidate(true);
        info.setUserName("your@qq.com");
        info.setPassword("授權碼"); // 非 QQ 密碼
        info.setFromAddress("your@qq.com");
        info.setToAddress("target@163.com");
        info.setSubject("JavaMail 測試 - " + System.currentTimeMillis());
        info.setContent("

HTML 郵件測試

包含中文內容

"); info.setAttachFileNames(new String[]{"D:/test.pdf", "D:/image.png"}); SimpleMailSender sender = new SimpleMailSender(); sender.sendAttachMail(info); // 一鍵發送帶附件 HTML 郵件 } }

避坑指南

  1. 新註冊郵箱無法發送:需養號一段時間或開啟「客戶端授權」
  2. SMTP 主機與發件人域名不匹配:用 163 SMTP 必須用 163 郵箱發件
  3. 中文附件名亂碼:必須用 MimeUtility.encodeText() 編碼
  4. 連接超時:檢查防火牆、端口(25/465/587)、SSL 配置
  5. 大附件發送失敗:調大 mail.smtp.sendpartial、分片發送或上傳雲存儲發鏈接
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved