JavaMail 是 Java 平台發送和接收郵件的標準 API,基於 MIME 協議,支持文本、HTML、附件、內嵌圖片等豐富郵件格式。
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>2.0.1</version>
</dependency>
Session.getInstance(props, authenticator)。transport.connect(host, user, pass)。transport.sendMessage(msg, recipients),transport.close()。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");
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);
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);
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");
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 應用中集成穩健的郵件功能。