以下封裝了一個可直接用於生產環境的 MailSender 類別,支援單發、群發、HTML 內容與附件編碼處理:
public class MailSender {
// ... 屬性定義(host, fromAddr, username, password 等) ...
/** 發送單一郵件 */
public void sendMail() throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", getHost());
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(getFromAddr()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(getToAddr()));
message.setSubject(getTitle());
// 建立多部分內容:HTML 正文 + 附件
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(getSendtext(), "text/html;charset=GBK");
multipart.addBodyPart(contentPart);
if (getAttachPath() != null && getAttachName() != null) {
BodyPart attachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource(getAttachPath());
attachmentPart.setDataHandler(new DataHandler(source));
// 附件檔名編碼,解決中文亂碼
BASE64Encoder enc = new BASE64Encoder();
attachmentPart.setFileName("=?GBK?B?" + enc.encode(getAttachName().getBytes()) + "?=");
multipart.addBodyPart(attachmentPart);
}
message.setContent(multipart);
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(getHost(), getUsername(), getPassword());
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
/** 群發郵件 */
public void sendMails() throws Exception {
// 類似 sendMail,差異在於使用 setRecipients 設定多個收件人
InternetAddress[] address = new InternetAddress[getMutliTo().length];
for (int i = 0; i < getMutliTo().length; i++) {
address[i] = new InternetAddress(getMutliTo()[i]);
}
message.setRecipients(Message.RecipientType.TO, address);
// 其餘邏輯同 sendMail
}
// Getter/Setter 略...
}
# Email 設定
host=smtp.163.com
username=your_account
password=your_password
fromadd=your_account@163.com
BASE64Encoder 搭配 MIME 編碼格式 =?charset?B?encoded?=,確保中文附件名在各郵件客戶端正常顯示。Transport 連線,避免連線洩漏。JavaMailSender 可進一步簡化配置與異常處理。