在 build.gradle 添加 JavaMail for Android (輕量級移植):
dependencies {
implementation "com.sun.mail:android-mail:1.6.7"
implementation "com.sun.mail:android-activation:1.6.7"
}
或複製 mail.jar, activation.jar, additional.jar 到 libs/。
public class MailSender extends Authenticator {
private final String host, port, sport, user, pass, from;
private final boolean auth, debuggable;
private final Multipart multipart = new MimeMultipart();
public MailSender(String host, String port, String user, String pass) {
this.host = host; this.port = port; this.sport = port;
this.user = user; this.pass = pass; this.from = user;
this.auth = true; this.debuggable = false;
fixMailCap();
}
private void fixMailCap() {
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
private Properties buildProps() {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.socketFactory.port", sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
if (auth) props.put("mail.smtp.auth", "true");
if (debuggable) props.put("mail.debug", "true");
return props;
}
public boolean send(String to, String subject, String body, List attachments) {
try {
Session session = Session.getInstance(buildProps(), this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
// 正文
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(body, "text/html; charset=utf-8");
multipart.addBodyPart(textPart);
// 附件
if (attachments != null) {
for (String path : attachments) {
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile(new File(path));
multipart.addBodyPart(attachPart);
}
}
msg.setContent(multipart);
Transport.send(msg);
return true;
} catch (Exception e) {
Log.e("MailSender", "發送失敗", e);
return false;
}
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
}
// Kotlin 協程
lifecycleScope.launch(Dispatchers.IO) {
val sender = MailSender("smtp.gmail.com", "465", "your@gmail.com", "app_password")
val ok = sender.send(
to = "target@example.com",
subject = "測試郵件",
body = "Hello
來自 Android App
",
attachments = listOf("/sdcard/Pictures/photo.jpg")
)
withContext(Dispatchers.Main) {
toast(if (ok) "發送成功" else "發送失敗")
}
}
| 服務商 | SMTP Host | Port | 加密 | 備註 |
|---|---|---|---|---|
| Gmail | smtp.gmail.com | 465 | SSL | 需開啟「兩步驗證」生成「應用專用密碼」 |
| Outlook/Hotmail | smtp-mail.outlook.com | 587 | STARTTLS | port 587 + STARTTLS |
| QQ 郵箱 | smtp.qq.com | 465/587 | SSL/STARTTLS | 需開啟 SMTP 服務獲取授權碼 |
| 163 郵箱 | smtp.163.com | 465/994 | SSL | 需開啟客戶端授權密碼 |
| 企業郵箱 | 自定義 | 465/587 | SSL/STARTTLS | 諮詢 IT 管理員 |
<uses-permission android:name="android.permission.INTERNET" />SSLSocketFactory-keep class com.sun.mail.** { *; } -keep class javax.mail.** { *; } -keep class javax.activation.** { *; }| 異常 | 原因 | 解決 |
|---|---|---|
| AuthenticationFailedException | 用戶名/密碼錯誤、未開啟 SMTP/授權碼 | 檢查郵箱設置、使用應用專用密碼 |
| MessagingException: Could not connect to SMTP host | 網絡不通、端口/加密方式錯誤、防火牆攔截 | Telnet 測試端口、切換 465/587、檢查代理 |
| CertificateException / SSLHandshakeException | 證書不信任、系統時間錯誤 | 同步時間、信任系統 CA、或自定義 TrustManager (僅測試) |
| MessagingException: Invalid address | 收件人格式錯誤 | 用 InternetAddress.parse() 解析、過濾空字符串 |
基於 JavaMail 封裝 MailSender 類,配合 Kotlin 協程在 IO 線程發送,支持 HTML 正文、多附件、多收件人、主流 SMTP 服務商。關鍵點:權限聲明、子線程執行、授權碼而非登錄密碼、SSL/TLS 配置匹配、混淆保留、敏感信息不硬編碼。若需更簡單方案,可考慮調用系統 ACTION_SEND Intent 唤起郵件客戶端,或接入 SendGrid/Mailgun 等郵件 API 服務 (HTTP 方式,無需 SMTP)。