在 Android 上以 JavaMail 寄送郵件時,若原本的工具類別只支援純文字,要加上附件其實不必大改架構——關鍵是把信件內容從單一 body 改為 multipart 結構。
原本的 GMailSender 用 DataHandler 把本文塞進 MimeMessage。要支援附件,就再建一個 MimeBodyPart 承載檔案,然後用 MimeMultipart("mixed") 把本文與附件組裝起來,最後一次 setContent() 交給信件物件即可。
在 GMailSender.java 中加入以下方法:
public void send_mail_file(String str_title, String str_body,
String str_from_mail, String str_to_mail, String str_file_path) {
MimeMessage message = new MimeMessage(session); // Define message
DataHandler handler = new DataHandler(new ByteArrayDataSource(
str_body.getBytes(), "text/plain"));
try {
message.setFrom(new InternetAddress(str_from_mail)); // Set the from address
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
str_to_mail));// Set the to address
message.setSubject(str_title);// Set the subject
message.setDataHandler(handler);
} catch (Exception e) {
}
MimeBodyPart attachPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(str_file_path); // 打開要發送的文件
try {
attachPart.setDataHandler(new DataHandler(fds));
attachPart.setFileName(fds.getName());
} catch (MessagingException e) {
e.printStackTrace();
}
MimeMultipart allMultipart = new MimeMultipart("mixed"); // 附件
try {
allMultipart.addBodyPart(attachPart);// 添加
message.setContent(allMultipart);
message.saveChanges();
Transport.send(message);// 開始發送
} catch (MessagingException e) {
e.printStackTrace();
}
}
呼叫這個方法並傳入檔案路徑,就能把附件一起寄出。
第一,Android 上寄信需要網路權限,AndroidManifest.xml 中的 INTERNET 一定要加。第二,Transport.send() 屬阻塞操作,不可放在主執行緒,請改用 AsyncTask、執行緒或 WorkManager,否則會觸發 NetworkOnMainThreadException。第三,若附件位於外部儲存媒體,需處理讀取權限與 FileProvider 分享;同時建議為 FileDataSource 加上檔案存在性檢查,避免把例外交給空白的 catch 吞掉。第四,示例中的 catch (Exception e) {} 是空區塊,正式環境請務必補上日誌,否則寄信失敗時你會完全不知道原因。