發送郵件是企業級應用的高頻需求。本例封裝了一個功能完備的 Mail 工具類,支援 SMTP 認證、多附件、HTML/純文字正文、中文主旨編碼(GB2312),並提供流暢的 Setter 鏈式調用風格,可直接整合專案使用。
transferChinese() 使用 MimeUtility.encodeText() 依 RFC 2047 標準進行 Base64 編碼(=?GB2312?B?...?=),解決郵件客戶端顯示亂碼問題。Vector 維護附件路徑列表,attachfile() 疊加,發送時迴圈構建 MimeBodyPart + FileDataSource 加入 MimeMultipart。props.put("mail.smtp.auth", "true") + 自定義 Authenticator 實作 getPasswordAuthentication()。public boolean sendMail() {
// 1. 建立 Session (含認證)
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
// 2. 構建 MimeMessage
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
msg.setSubject(transferChinese(subject)); // 中文編碼
// 3. 構建 Multipart 容器
Multipart mp = new MimeMultipart();
// 3.1 加入正文
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent.setText(content); // 或 setContent(html, "text/html;charset=UTF-8")
mp.addBodyPart(mbpContent);
// 3.2 加入附件
for (String fname : file) {
MimeBodyPart mbpFile = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fname);
mbpFile.setDataHandler(new DataHandler(fds));
mbpFile.setFileName(MimeUtility.encodeText(fds.getName())); // 附件名也需編碼
mp.addBodyPart(mbpFile);
}
// 4. 發送
msg.setContent(mp);
msg.setSentDate(new Date());
Transport.send(msg);
return true;
}
setContent(html, "text/html;charset=UTF-8"),附件檔名同樣需 MimeUtility.encodeText(),避免中文附件名亂碼。props.put("mail.smtp.ssl.enable", "true") 或 props.put("mail.smtp.starttls.enable", "true"),並對應連接埠。mail.smtp.connectiontimeout, mail.smtp.timeout;超大附件考慮分卷或雲存儲連結替代。public static void main(String[] args) {
Mail sendmail = new Mail();
sendmail.setHost("smtp.sohu.com");
sendmail.setUserName("your_account");
sendmail.setPassWord("your_password");
sendmail.setTo("recipient@example.com");
sendmail.setFrom("sender@sohu.com");
sendmail.setSubject("測試郵件 - 中文主旨");
sendmail.setContent("這是一封帶附件的測試郵件!");
sendmail.attachfile("c:\\test.txt");
sendmail.attachfile("DND.jar");
sendmail.sendMail();
}