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

如何使用 JavaMail 發送郵件完整教程

     編輯:Java 相關知識

概述

JavaMail 是 Java 平台發送和接收郵件的標準 API,基於 MIME 協議,支持文本、HTML、附件、內嵌圖片等豐富郵件格式。

核心依賴

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

發送郵件五步驟

  1. 配置屬性:SMTP 主機、端口、認證、SSL/TLS 等。
  2. 創建 Session:Session.getInstance(props, authenticator)。
  3. 構建 MimeMessage:設置發件人、收件人、主題、內容(見下文)。
  4. 獲取 Transport 並連接:transport.connect(host, user, pass)。
  5. 發送並關閉:transport.sendMessage(msg, recipients),transport.close()。

常見郵件類型構建

1. 純文本/HTML 郵件

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("me@gmail.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("you@example.com"));
msg.setSubject("測試郵件");
msg.setContent("<h1>HTML 內容</h1>", "text/html;charset=UTF-8");

2. 帶附件郵件

MimeMultipart mp = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent("正文", "text/html;charset=UTF-8");
mp.addBodyPart(textPart);

MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile(new File("report.pdf")); // JDK 1.6+
mp.addBodyPart(attachPart);
mp.setSubType("mixed");
msg.setContent(mp);

3. 內嵌圖片郵件

MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("圖片: <img src='cid:logo'>", "text/html;charset=UTF-8");

MimeBodyPart imgPart = new MimeBodyPart();
imgPart.attachFile(new File("logo.png"));
imgPart.setContentID("<logo>"); // CID

MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(htmlPart);
mp.addBodyPart(imgPart);
mp.setSubType("related");
msg.setContent(mp);

關鍵配置示例

Gmail (SSL 465)

props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.auth", "true");

QQ/163 (STARTTLS 587)

props.put("mail.smtp.host", "smtp.qq.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");

最佳實踐

  • 使用 Authenticator 封裝密碼,避免明文硬編碼。
  • 生產環境啟用 session.setDebug(false)。
  • 異步發送(線程池/消息隊列)避免阻塞主業務。
  • 捕獲 MessagingException 區分認證失敗、網絡錯誤、郵箱不存在等。

總結

JavaMail 提供了完整的 MIME 郵件構建與 SMTP 發送能力,掌握其核心對象模型與配置細節,即可在任何 Java 應用中集成穩健的郵件功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved