基於 JavaMail API 實現郵件發送功能,以搜狐郵箱 SMTP 服務為例,涵蓋純文本、HTML 富文本及帶附件的多種場景。
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
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("帶附件郵件發送成功!");
}
mail.smtp.ssl.enable=true 或 mail.smtp.starttls.enable=true。MimeUtility.encodeText() 防止亂碼。| 異常 | 原因 | 解決 |
|---|---|---|
| AuthenticationFailedException | 賬號/授權碼錯誤、未開啟 SMTP | 檢查郵箱設置,使用授權碼 |
| MessagingException: Could not connect to SMTP host | 網絡不通、端口錯誤、防火牆攔截 | telnet 測試端口連通性,確認 SSL/TLS 設置 |
| UnsupportedEncodingException | 附件名編碼問題 | 使用 MimeUtility.encodeText() |