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

Java 發送郵件完整指南:無附件、帶附件與 HTML 郵件實現

     編輯:Java 綜合教學

Java 發送郵件完整指南:無附件、帶附件與 HTML 郵件實現

基於 JavaMail API 實現郵件發送功能,以搜狐郵箱 SMTP 服務為例,涵蓋純文本、HTML 富文本及帶附件的多種場景。

核心依賴

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

場景一:發送簡單文本/HTML 郵件(無附件)

public void sendSimpleMail() throws Exception {
    // 1. 配置郵件服務器屬性
    Properties props = new Properties();
    props.setProperty("mail.host", "smtp.sohu.com");
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.smtp.port", "25"); // 或 465/587 (SSL/TLS)
    props.setProperty("mail.smtp.ssl.enable", "false"); // 啟用 SSL 設為 true

    // 2. 認證器
    Authenticator auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("your_email@sohu.com", "your_password");
        }
    };

    // 3. 獲取 Session
    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(true); // 開啟調試模式,控制台輸出通信詳情

    // 4. 構建郵件消息
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress("your_email@sohu.com"));
    msg.setRecipient(RecipientType.TO, new InternetAddress("recipient@example.com"));
    msg.setSubject("測試郵件主題");
    // 設置 HTML 內容
    msg.setContent("<h1>Hello JavaMail!</h1><p>這是一封<b>HTML</b>郵件。</p>", "text/html;charset=UTF-8");

    // 5. 發送
    Transport.send(msg);
    System.out.println("郵件發送成功!");
}

場景二:發送帶附件的郵件

public void sendMailWithAttachment() throws Exception {
    Properties props = new Properties();
    props.setProperty("mail.host", "smtp.sohu.com");
    props.setProperty("mail.smtp.auth", "true");
    // ... 其他屬性同場景一

    Authenticator auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("your_email@sohu.com", "your_password");
        }
    };

    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress("your_email@sohu.com"));
    msg.setRecipient(RecipientType.TO, new InternetAddress("recipient@example.com"));
    msg.setSubject("帶附件的郵件");

    // 關鍵:使用 MimeMultipart 組裝多部分內容
    MimeMultipart multipart = new MimeMultipart();

    // 部分1:郵件正文(HTML)
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent("<p>你好,請查收附件。</p>", "text/html;charset=UTF-8");
    multipart.addBodyPart(textPart);

    // 部分2:附件
    MimeBodyPart attachPart = new MimeBodyPart();
    File file = new File("D:/documents/report.pdf");
    attachPart.attachFile(file);
    // 解決中文文件名亂碼
    attachPart.setFileName(MimeUtility.encodeText(file.getName()));
    multipart.addBodyPart(attachPart);

    // 設置郵件整體內容
    msg.setContent(multipart);

    Transport.send(msg);
    System.out.println("帶附件郵件發送成功!");
}

關鍵注意點

  • SMTP 端口與加密:25 端口常被封鎖,建議使用 465 (SSL) 或 587 (STARTTLS),需設置 mail.smtp.ssl.enable=true 或 mail.smtp.starttls.enable=true。
  • 授權碼而非密碼:現代郵箱多需開啟「SMTP 服務」並生成「授權碼」作為密碼。
  • 中文附件名編碼:必須用 MimeUtility.encodeText() 防止亂碼。
  • 大附件分片:超過郵箱限制(通常 20-50MB)需分卷壓縮或使用雲存儲鏈接替代。
  • 異步發送:生產環境建議放入消息隊列(如 RabbitMQ/Kafka)由消費者異步發送,避免阻塞業務線程。

常見異常排查

異常 原因 解決
AuthenticationFailedException 賬號/授權碼錯誤、未開啟 SMTP 檢查郵箱設置,使用授權碼
MessagingException: Could not connect to SMTP host 網絡不通、端口錯誤、防火牆攔截 telnet 測試端口連通性,確認 SSL/TLS 設置
UnsupportedEncodingException 附件名編碼問題 使用 MimeUtility.encodeText()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved