指定多收件人有兩種方式:
Transport.sendMessage(msg, addresses) 接收 Address[]。msg.setRecipients(RecipientType.TO, InternetAddress.parse("a@b.com,c@d.com")) 解析字符串。身份驗證需實作 Authenticator 並覆寫 getPasswordAuthentication(),回傳 PasswordAuthentication(user, pass)。取得 Session 時傳入:
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
props.put("mail.host", "smtp.163.com");
Session session = Session.getInstance(props, new Authenticator() { ... });
session.setDebug(true);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("sender@163.com"));
msg.setSubject("JavaMail 測試");
msg.setContent("HTML 內容", "text/html;charset=gbk");
msg.setRecipients(RecipientType.TO, InternetAddress.parse("a@qq.com,b@qq.com"));
Transport.send(msg);
MIME 多部分訊息組合關係:
mixed:混合關係(附件與正文並列)。related:關聯關係(HTML 正文與內嵌資源)。alternative:替代關係(純文字版與 HTML 版二選一)。Message message = new MimeMessage(session);
message.setSubject("複雜郵件測試");
message.setFrom(new InternetAddress("sender@163.com"));
message.setRecipients(RecipientType.TO, new Address[]{new InternetAddress("to@qq.com")});
// 最外層 mixed:正文 + 附件
MimeMultipart mixed = new MimeMultipart("mixed");
message.setContent(mixed);
// 正文部分(related:HTML + 圖片)
MimeBodyPart contentPart = new MimeBodyPart();
MimeMultipart related = new MimeMultipart("related");
contentPart.setContent(related);
// HTML 正文
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("Hello
", "text/html;charset=UTF-8");
related.addBodyPart(htmlPart);
// 內嵌圖片
MimeBodyPart imgPart = new MimeBodyPart();
DataSource imgDs = new FileDataSource("F:/pic/logo.jpg");
imgPart.setDataHandler(new DataHandler(imgDs));
imgPart.setHeader("Content-ID", "");
related.addBodyPart(imgPart);
mixed.addBodyPart(contentPart);
// 附件 1
MimeBodyPart att1 = new MimeBodyPart();
DataSource ds1 = new FileDataSource("G:/ebook/oracle.txt");
att1.setDataHandler(new DataHandler(ds1));
att1.setFileName("oracle.txt");
mixed.addBodyPart(att1);
// 附件 2(中文檔名需編碼)
MimeBodyPart att2 = new MimeBodyPart();
DataSource ds2 = new FileDataSource("G:/ebook/帳號.txt");
att2.setDataHandler(new DataHandler(ds2));
att2.setFileName(MimeUtility.encodeText("帳號.txt"));
mixed.addBodyPart(att2);
message.saveChanges();
Transport.send(message);
MimeMessage:整封郵件。MimeBodyPart:一個 MIME 部分(正文、附件、圖片)。MimeMultipart:多部分組合容器,subtype 決定組合關係。DataSource / DataHandler:封裝資料來源(檔案、URL、位元組陣列)。MimeUtility.encodeText():處理中文檔名/主題編碼。