萬盛學電腦網

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

Android 後台發送郵件收集 Crash 日誌:JavaMail API 實作與現代替代方案

場景

App 發布後自動收集未捕獲異常,透過背景執行緒發送郵件到開發者郵箱,**無需用戶干預**,適合無伺服器端的小團隊/個人開發者。

依賴:JavaMail for Android

標準 `javax.mail` 在 Android 上需移植,推薦使用移植版:

// build.gradle
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 {
    private final String host;      // smtp.qq.com
    private final String port;      // "465" (SSL) 或 "587" (STARTTLS)
    private final String user;      // 發件郵箱
    private final String password;  // 授權碼 (非登入密碼)
    private final String from;
    private final String to;
    private final boolean ssl;

    public MailSender(String host, String port, String user, String password, String to, boolean ssl) {
        this.host = host; this.port = port; this.user = user; this.password = password;
        this.from = user; this.to = to; this.ssl = ssl;
    }

    public boolean send(String subject, String body, File... attachments) {
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        if (ssl) {
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.port", port);
        } else {
            props.put("mail.smtp.starttls.enable", "true");
        }

        Session session = Session.getInstance(props, new Authenticator() {
            @Override protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });
        session.setDebug(false); // 開發時可設 true 看日誌

        try {
            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());

            // 建立 Multipart (文字 + 附件)
            Multipart multipart = new MimeMultipart();
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setContent(body, "text/html; charset=utf-8");
            multipart.addBodyPart(textPart);

            for (File file : attachments) {
                if (file.exists()) {
                    MimeBodyPart attachPart = new MimeBodyPart();
                    attachPart.attachFile(file);
                    multipart.addBodyPart(attachPart);
                }
            }
            msg.setContent(multipart);
            Transport.send(msg);
            return true;
        } catch (MessagingException | IOException e) {
            Log.e("MailSender", "發送失敗", e);
            return false;
        }
    }
}

全域異常捕獲與自動發送

public class MyApplication extends Application {
    private static final String CRASH_DIR = "crash_logs";
    private MailSender mailSender;

    @Override
    public void onCreate() {
        super.onCreate();
        mailSender = new MailSender("smtp.qq.com", "465", "dev@example.com", "auth_code", "dev@example.com", true);
        
        Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
            handleCrash(throwable);
            // 給系統預設處理器一點時間上傳,再殺進程
            try { Thread.sleep(3000); } catch (InterruptedException ignored) {}
            Process.killProcess(Process.myPid());
            System.exit(10);
        });
    }

    private void handleCrash(Throwable throwable) {
        // 1. 寫入本地檔案
        File dir = new File(getExternalFilesDir(null), CRASH_DIR);
        if (!dir.exists()) dir.mkdirs();
        String fileName = "crash_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()) + ".log";
        File logFile = new File(dir, fileName);
        try (PrintWriter pw = new PrintWriter(new FileWriter(logFile))) {
            throwable.printStackTrace(pw);
            // 附加裝置資訊
            pw.println("\n--- Device Info ---");
            pw.println("Model: " + Build.MODEL);
            pw.println("Android: " + Build.VERSION.RELEASE);
            pw.println("App Version: " + BuildConfig.VERSION_NAME);
        } catch (IOException ignored) {}

        // 2. 背景發送郵件 (不阻塞主執行緒)
        new Thread(() -> {
            String subject = "[Crash] " + getPackageName() + " v" + BuildConfig.VERSION_NAME;
            String body = "時間: " + new Date() + "\n裝置: " + Build.MODEL + "\n\n" + Log.getStackTraceString(throwable);
            mailSender.send(subject, body, logFile);
        }).start();
    }
}

Manifest 配置

<application
    android:name=".MyApplication"
    android:allowBackup="true" ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- API 28 以下 -->
</application>

重要避坑指南

坑點解決方案
QQ/163/Outlook 郵箱拒收必須開啟 **SMTP 服務** 並使用 **授權碼** (非登入密碼);SSL 埠 465/994,STARTTLS 埠 587。
郵件進垃圾箱/被退信主題避免敏感詞、內容加 DKIM/SPF (需域名)、控制發送頻率 (每小時 < 10 封)、附件不超 10MB。
Android 7.0+ FileUriExposedException附件必須用 **FileProvider** 生成 `content://` Uri,並加 `FLAG_GRANT_READ_URI_PERMISSION`。
主執行緒網路操作崩潰發送郵件**必須在背景執行緒** (Thread/Executor/Coroutine/WorkManager)。
用戶隱私合規隱私政策說明收集 Crash 日誌,**敏感資訊 (Token、位置、通訊錄) 必須脫敏/過濾**。
Doze/待機模式發送失敗改用 **WorkManager** 設定 `setRequiredNetworkType(CONNECTED)` 確保有網時執行。

現代替代方案 (強烈推薦)

  • Firebase Crashlytics:免費、即時、分組、趨勢、關鍵指標、無需自建郵件伺服器。
  • Sentry / Bugly / Umeng:同類成熟 SDK。
  • 自建伺服器 + WorkManager 上傳:JSON 上傳,靈活查詢、告警、關聯版本/用戶。

郵件方案僅作為**無後端資源時的臨時過渡**,生產環境請接入專業崩潰收集平台。

copyright © 萬盛學電腦網 all rights reserved