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

Java 基於 SMTP 發送郵件完整實現指南

     編輯:Java 相關知識

核心依賴

需引入 JavaMail API(現屬 Jakarta EE):

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>2.0.1</version>
</dependency>

完整發送工具類

import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.Date;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MailUtil {
    private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);

    /**
     * 發送純文本郵件
     * @param smtpHost SMTP 服務器地址
     * @param username 郵箱用戶名
     * @param password 郵箱授權碼/密碼
     * @param subject 郵件主題
     * @param content 郵件正文
     * @param from 發件人郵箱
     * @param to 收件人郵箱(支持逗號分隔多個)
     */
    public static void send(String smtpHost, final String username, final String password,
                           String subject, String content, String from, String to) {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", smtpHost);
            props.put("mail.smtp.auth", "true");
            // SSL/TLS 配置(根據服務商要求)
            props.put("mail.smtp.ssl.enable", "true");     // SSL 465 端口
            props.put("mail.smtp.starttls.enable", "true"); // STARTTLS 587 端口
            props.put("mail.smtp.port", "465");             // 或 587

            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            session.setDebug(false); // 生產環境關閉調試

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject, "UTF-8");
            message.setText(content, "UTF-8");
            message.setSentDate(new Date());

            Transport.send(message);
            logger.info("郵件發送成功: {} -> {}", from, to);
        } catch (MessagingException e) {
            logger.error("郵件發送失敗: {}", e.getMessage(), e);
            throw new RuntimeException("郵件發送異常", e);
        }
    }
}

常見服務商 SMTP 配置

服務商SMTP 地址端口加密方式
QQ 郵箱smtp.qq.com465 / 587SSL / STARTTLS
163 郵箱smtp.163.com465 / 994SSL
Gmailsmtp.gmail.com465 / 587SSL / STARTTLS
Outlooksmtp.office365.com587STARTTLS

注意:現代郵箱多要求使用「授權碼」而非登錄密碼,需在郵箱設置中開啟 SMTP 服務並獲取授權碼。

進階功能擴展

發送 HTML 富文本郵件

MimeMessage message = new MimeMessage(session);
// ... 設置發件人、收件人、主題
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("

標題

內容

", "text/html;charset=UTF-8"); MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(htmlPart); message.setContent(multipart);

添加附件

MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(new File("/path/to/file.pdf"));
multipart.addBodyPart(attachmentPart);

異步發送(生產環境推薦)

@Async
public CompletableFuture<Void> sendAsync(...) {
    return CompletableFuture.runAsync(() -> send(...));
}

常見問題排查

  • 認證失敗:檢查用戶名/授權碼、是否開啟 SMTP 服務
  • 連接超時:檢查防火牆、端口、網絡連通性
  • 進垃圾箱:設置 SPF/DKIM/DMARC、避免敏感詞、使用正規域名
  • 中文亂碼:統一使用 UTF-8 編碼,MimeMessage.setSubject(text, "UTF-8")

最佳實踐總結

  1. 使用連接池管理 Session(如 Apache Commons Email 封裝)
  2. 異步發送解耦業務邏輯,配合重試機制
  3. 敏感信息(授權碼)存放於配置中心/密碼管理系統
  4. 記錄發送日誌便於追蹤和審計
  5. 考慮使用專業郵件服務(SendGrid、Amazon SES、阿里云邮件推送)提高送達率
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved