Android使用javax.mail发送crash邮件给自己

时间:2021-10-07 18:13:39

首先要手动添加三个jar包 mail、activation、additionnal

需要*下载链接:https://code.google.com/archive/p/javamail-android/downloads
百度云盘链接:https://pan.baidu.com/s/1vheC2JQKBfc35PXCb6OK_g

Android使用javax.mail发送crash邮件给自己

复制到libs目录下后对jar包点击右键 –> add as library ,如果没找到add as library但还是找不到类的话 点击file -> project structure -> app -> dependencies -> 右上角的+号 -> jar dependency 找到复制的三个jar包添加完成点击OK

java.lang.NoClassDefFoundError: javax.activation.DataHandler

错误原因是没有添加additionnal的jar包,因为activation和additionnal是配套使用的,在上面贴出来的Google下载链接也可以看到 (need additionnal.jar)

Android使用javax.mail发送crash邮件给自己

纯发送邮件请看大神博客:https://blog.csdn.net/xietansheng/article/details/51673073

如果不想看可以直接复制代码:https://github.com/jiaweizeng/JavaxMail(163发给QQ)修改为自己的邮箱和密码

注意事项:

1、是否开启SMTP服务,服务器地址

2、开启SMTP服务的话邮箱密码要填写邮箱授权码

3、发送邮件必须在子线程完成

4、网络权限,写到本地还要读写权限,6.0以上动态

5、关于只发一次,第二次就不发的问题(我也遇到,第二天回来上班就好了,只能帮你到这了,哈哈哈~)

Android使用javax.mail发送crash邮件给自己

Android使用javax.mail发送crash邮件给自己
Android使用javax.mail发送crash邮件给自己

发送crash邮件

传送门:https://github.com/jiaweizeng/CrashMail

初始化和权限的动态获取

package cn.hzjk.crashmail;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //在这里为应用设置异常处理程序,然后我们的程序才能捕获未处理的异常
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);
        Button btnCrash =findViewById(R.id.btn_crash);
        btnCrash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkStoragePermission();
            }
        });
    }
    private void checkStoragePermission() {
        int result = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_DENIED) {
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions(this, permissions, 0xa0);
        } else {
            new ArrayList<>().get(9);
        }
    }
    //权限申请回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode){
            case 0xa0:
                if (grantResults[0]==PackageManager.PERMISSION_DENIED){
                    Toast.makeText(this, "why ??????", Toast.LENGTH_SHORT).show();
                    return;
                }
                new ArrayList<>().get(9);
                break;
        }

    }
}

EmailUtil

package cn.hzjk.crashmail;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * Created by zjw on 2018/4/20.
 */

public class EmailUtil {

    class MyAuthenticator extends javax.mail.Authenticator {
        private String strUser;
        private String strPwd;

        public MyAuthenticator(String user, String password) {
            this.strUser = user;
            this.strPwd = password;
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPwd);
        }
    }

    public void sendMail(String toMail, String fromMail, String server,
                         String username, String password, String title, String body,
                         String attachment) throws Exception {

        Properties props = System.getProperties();// Get system properties
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议(JavaMail规范要求)
        props.put("mail.smtp.host", server);// Setup mail server

        props.put("mail.smtp.auth", "true");

        MyAuthenticator myauth = new MyAuthenticator(username, password);// Get
        // 发送邮件,和密码

        Session session = Session.getDefaultInstance(props, myauth);
        session.setDebug(true);                                 // 设置为debug模式, 可以查看详细的发送 log
        MimeMessage message = new MimeMessage(session); // Define message

        message.setFrom(new InternetAddress(fromMail)); // Set the from address
        // 接收邮箱

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                toMail));// 目标邮箱
        // address
        message.setSubject(title);// Set the subject 标题

        // message.setText(MimeUtility.encodeWord(body));// Set the content

        MimeMultipart allMultipart = new MimeMultipart("mixed");

        MimeBodyPart attachPart = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(attachment);
        attachPart.setDataHandler(new DataHandler(fds));
        attachPart.setFileName(MimeUtility.encodeWord(fds.getName()));

        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(body);// 邮件内容

        allMultipart.addBodyPart(attachPart);
        allMultipart.addBodyPart(textBodyPart);
        message.setContent(allMultipart);
        message.saveChanges();
        Transport.send(message);
    }

    /**
     * 设置邮件信息
     *  toMail
     *            接收邮箱
     *  account
     *            发送者邮箱
     *  password
     *            发送者邮箱密码
     *  server
     *            发送者邮箱服务器
     * @param title
     *            邮件标题
     * @param body
     *            邮件内容
     * @param path
     *            附件路径
     */
    public void sendMailS(final String body, final String path,final String title) {
        new Thread(new Runnable() {
            public void run() {
                // EmailUtil emailUtil = new EmailUtil();
                try {
                    String toMail = "@qq.com";
                    String account = "@163.com";
                    String password = "";
                    String server = "smtp.163.com";
                    // emailUtil.
                    sendMail(toMail, account, server, account, password, title,
                            body, path);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

CrashHandler

package cn.hzjk.crashmail;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import android.os.SystemClock;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by zjw on 2018/4/20.
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";
    private static final boolean DEBUG = true;
    private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/Email_info/log/";
    private static final String FILE_NAME = "log_";
    private String filepath;

    //log文件的后缀名
    private static final String FILE_NAME_SUFFIX = ".txt";

    private static CrashHandler sInstance = new CrashHandler();

    //系统默认的异常处理(默认情况下,系统会终止当前的异常程序)
    private Thread.UncaughtExceptionHandler mDefaultCrashHandler;

    private Context mContext;

    //构造方法私有,防止外部构造多个实例,即采用单例模式
    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return sInstance;
    }

    //这里主要完成初始化工作
    public void init(Context context) {
        //获取系统默认的异常处理器
        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
        //将当前实例设为系统默认的异常处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
        //获取Context,方便内部使用
        mContext = context.getApplicationContext();
    }

    /**
     * 这个是最关键的函数,当程序中有未被捕获的异常,系统将会自动调用#uncaughtException方法
     * thread为出现未捕获异常的线程,ex为未捕获的异常,有了这个ex,我们就可以得到异常信息。
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            //导出异常信息到SD卡中
            dumpExceptionToSDCard(ex);
            //这里可以通过网络上传异常信息到服务器,便于开发人员分析日志从而解决bug
            uploadExceptionToServer();
            SystemClock.sleep(1500);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //打印出当前调用栈信息
        ex.printStackTrace();

        //如果系统提供了默认的异常处理器,则交给系统去结束我们的程序,否则就由我们自己结束自己
        if (mDefaultCrashHandler != null) {
            mDefaultCrashHandler.uncaughtException(thread, ex);
        } else {
            Process.killProcess(Process.myPid());
        }

    }

    private void dumpExceptionToSDCard(Throwable ex) throws IOException {
        //如果SD卡不存在或无法使用,则无法把异常信息写入SD卡
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (DEBUG) {
                Log.w(TAG, "sdcard unmounted,skip dump exception");
                return;
            }
        }

        File dir = new File(PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        long current = System.currentTimeMillis();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
        //以当前时间创建log文件
        filepath = PATH + FILE_NAME+ current+ FILE_NAME_SUFFIX;
        File file = new File(filepath);

        Log.e(TAG, "fiel="+file);
        try {
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
            //导出发生异常的时间
            pw.println(time);

            //导出手机信息
            dumpPhoneInfo(pw);

            pw.println();
            //导出异常的调用栈信息
            ex.printStackTrace(pw);

            pw.close();
        } catch (Exception e) {
            Log.e(TAG, "dump crash info failed");
        }
    }

    private void dumpPhoneInfo(PrintWriter pw) throws NameNotFoundException {
        //应用的版本名称和版本号
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.print("App Version: ");
        pw.print(pi.versionName);
        pw.print('_');
        pw.println(pi.versionCode);

        //android版本号
        pw.print("OS Version: ");
        pw.print(Build.VERSION.RELEASE);
        pw.print("_");
        pw.println(Build.VERSION.SDK_INT);

        //手机制造商
        pw.print("Vendor: ");
        pw.println(Build.MANUFACTURER);

        //手机型号
        pw.print("Model: ");
        pw.println(Build.MODEL);

        //cpu架构
        pw.print("CPU ABI: ");
        pw.println(Build.CPU_ABI);
    }

    private void uploadExceptionToServer() {
        //TODO Upload Exception Message To Your Web Server
        EmailUtil emailUtil = new EmailUtil();
        emailUtil.sendMailS(getbody(), filepath,getAppName()+"CrashReport");
        Log.e(TAG, "sendemali");
    }

    public String getbody(){
        StringBuffer sb=new StringBuffer();
        try {
            dumpPhoneInfo(sb);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sb.toString();
    }
    public void dumpPhoneInfo(StringBuffer pw) throws NameNotFoundException {
        //应用的版本名称和版本号
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.append("App Version: ");
        pw.append(pi.versionName);
        pw.append('_');
        pw.append(pi.versionCode);
        pw.append("\n");

        //android版本号
        pw.append("OS Version: ");
        pw.append(Build.VERSION.RELEASE);
        pw.append("_");
        pw.append(Build.VERSION.SDK_INT);
        pw.append("\n");

        //手机制造商
        pw.append("Vendor: ");
        pw.append(Build.MANUFACTURER);
        pw.append("\n");

        //手机型号
        pw.append("Model: ");
        pw.append(Build.MODEL);
        pw.append("\n");

        //cpu架构
        pw.append("CPU ABI: ");
        pw.append(Build.CPU_ABI);
        pw.append("\n");
    }
    /**
     * 获取应用程序名称
     */
    public  String getAppName()
    {
        try
        {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    mContext.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return mContext.getResources().getString(labelRes);
        } catch (NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}

Android使用javax.mail发送crash邮件给自己
Android使用javax.mail发送crash邮件给自己

不过我并不喜欢附件的形式,因为附件可能会有个有效期或者邮箱有容量的限制,超过期限或者容量可能就不能下载了,所以我要把全部报告都打印在邮件的正文里,修改了如下方法:

传送门:https://github.com/jiaweizeng/CrashDetailMail

 public void dumpPhoneInfo(StringBuffer pw) throws NameNotFoundException {
        //应用的版本名称和版本号
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        pw.append("App Version: ");
        pw.append(pi.versionName);
        pw.append('_');
        pw.append(pi.versionCode);
        pw.append("\n");

        //android版本号
        pw.append("OS Version: ");
        pw.append(Build.VERSION.RELEASE);
        pw.append("_");
        pw.append(Build.VERSION.SDK_INT);
        pw.append("\n");

        //手机制造商
        pw.append("Vendor: ");
        pw.append(Build.MANUFACTURER);
        pw.append("\n");

        //手机型号
        pw.append("Model: ");
        pw.append(Build.MODEL);
        pw.append("\n");

        //cpu架构
        pw.append("CPU ABI: ");
        pw.append(Build.CPU_ABI);
        pw.append("\n");

        try {
            BufferedReader br = new BufferedReader(new FileReader(new File(filepath)));
            String line;
            while ((line=br.readLine())!=null){
                pw.append(line);
                pw.append("\n");
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

最后结果如下:

Android使用javax.mail发送crash邮件给自己

Android使用javax.mail发送crash邮件给自己

https://www.jianshu.com/p/a322e1b2a612