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

Java 郵件發送完全指南:多收件人、HTML 內容與附件實戰

     編輯:Java 程式設計入門

核心依賴

需引入 JavaMail API(javax.mail)與 Activation Framework(javax.activation),並準備 SMTP 服務器帳號(示例使用 163 郵箱)。

完整發送類 SendMailTest

public class SendMailTest {
    public static void main(String[] args) {
        String title = "titleTest";
        String from = "sir_znp@163.com";
        String[] sendTo = {"znp@163.net", "sir_znp@163.com"};
        String content = "mail test!!!!!!<br><a href=#>aaa</a>"; // 支持 HTML
        String[] fileNames = {"F:\\music\\text1.txt,text1.txt", "F:\\music\\text2.txt,text2.txt"}; // 路徑,顯示名

        try {
            sendmail(title, from, sendTo, content, fileNames, "text/html;charset=gb2312");
        } catch (Exception ex) { ex.printStackTrace(); }
    }

    public static void sendmail(String subject, String from, String[] to,
                                String text, String[] filenames, String mimeType) throws Exception {

        Properties props = System.getProperties();
        String smtp = "smtp.163.com";
        String user = "sir_znp";
        String pass = "123";

        props.put("mail.smtp.host", smtp);
        props.put("mail.smtp.auth", "true");

        Session mailSession = Session.getInstance(props, new EmailAuthenticator(user, pass));
        Transport transport = mailSession.getTransport("smtp");

        MimeMessage mimeMsg = new MimeMessage(mailSession);
        if (from != null) mimeMsg.setFrom(new InternetAddress(from));

        InternetAddress[] sendTo = Arrays.stream(to).map(InternetAddress::new).toArray(InternetAddress[]::new);
        mimeMsg.setRecipients(Message.RecipientType.TO, sendTo);
        mimeMsg.setSubject(subject, "gb2312");

        // 郵件正文
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent(text, mimeType);

        // 組裝多部分:正文 + 附件
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        for (String fn : filenames) {
            String[] parts = fn.split(",");
            String filePath = parts[0];
            String displayName = parts.length > 1 ? parts[1] : new File(filePath).getName();

            MimeBodyPart attachPart = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(filePath);
            attachPart.setDataHandler(new DataHandler(fds));
            attachPart.setFileName(MimeUtility.encodeText(displayName)); // 解決中文附件名亂碼
            multipart.addBodyPart(attachPart);
        }

        mimeMsg.setContent(multipart);
        mimeMsg.setSentDate(new Date());
        mimeMsg.saveChanges();

        transport.send(mimeMsg);
        transport.close();
    }
}

認證器 EmailAuthenticator

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

關鍵點總結

  • 多收件人:InternetAddress[] 數組傳給 setRecipients。
  • HTML 正文:setContent(text, "text/html;charset=gb2312")。
  • 附件處理:MimeMultipart 組合 MimeBodyPart,FileDataSource 讀取文件,MimeUtility.encodeText 編碼文件名防亂碼。
  • 編碼建議:主題、正文、附件名統一指定 charset(如 gb2312 或 UTF-8),避免中文亂碼。
  • 生產環境:敏感信息(密碼、SMTP 地址)應外置到配置文件,使用連接池或異步發送提升性能。

常見問題排查

現象可能原因對策
發送失敗:Authentication failed用戶名/密碼錯誤、未開啟 SMTP 服務、需授權碼郵箱設置中開啟 SMTP 並獲取授權碼替代密碼
附件名亂碼未編碼文件名使用 MimeUtility.encodeText(displayName)
連接超時防火牆/網絡/端口(25/465/587)檢查網絡通達性,嘗試 SSL/TLS 端口
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved