萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 後台靜默發送郵件:JavaMail API 封裝與附件支持完整實現

核心依賴

在 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 服務商配置

服務商SMTP HostPort加密備註
Gmailsmtp.gmail.com465SSL需開啟「兩步驗證」生成「應用專用密碼」
Outlook/Hotmailsmtp-mail.outlook.com587STARTTLSport 587 + STARTTLS
QQ 郵箱smtp.qq.com465/587SSL/STARTTLS需開啟 SMTP 服務獲取授權碼
163 郵箱smtp.163.com465/994SSL需開啟客戶端授權密碼
企業郵箱自定義465/587SSL/STARTTLS諮詢 IT 管理員

關鍵注意事項

  1. 網絡權限:<uses-permission android:name="android.permission.INTERNET" />
  2. 子線程執行:網絡操作嚴禁主線程,使用 Coroutines/RxJava/ExecutorService
  3. 附件大小限制:多數郵箱限制 20~50MB,大文件請上傳雲存儲後發送鏈接
  4. SSL/TLS 證書驗證:Android 7+ 默認強制驗證,自簽名證書需自定義 SSLSocketFactory
  5. 混淆規則:-keep class com.sun.mail.** { *; } -keep class javax.mail.** { *; } -keep class javax.activation.** { *; }
  6. 安全性:密碼/授權碼**切勿硬編碼**,應從加密配置/服務端下發/用戶輸入獲取

常見錯誤排查

異常原因解決
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)。

copyright © 萬盛學電腦網 all rights reserved