需引入 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 地址 | 端口 | 加密方式 |
|---|---|---|---|
| QQ 郵箱 | smtp.qq.com | 465 / 587 | SSL / STARTTLS |
| 163 郵箱 | smtp.163.com | 465 / 994 | SSL |
| Gmail | smtp.gmail.com | 465 / 587 | SSL / STARTTLS |
| Outlook | smtp.office365.com | 587 | STARTTLS |
注意:現代郵箱多要求使用「授權碼」而非登錄密碼,需在郵箱設置中開啟 SMTP 服務並獲取授權碼。
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(...));
}
MimeMessage.setSubject(text, "UTF-8")