Skip to content

Instantly share code, notes, and snippets.

@xmaihh
Last active July 23, 2019 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmaihh/fef3da7f591b78290db541ee57903900 to your computer and use it in GitHub Desktop.
Save xmaihh/fef3da7f591b78290db541ee57903900 to your computer and use it in GitHub Desktop.
Java邮件发送程序
public class SendEmailUtils {

    /**
     * 邮件发送程序
     *
     *           接收邮件的address
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     * @param attachmentPath
     *            附件路径
     * @param attachmentName
     *            附件名称
     * @throws Exception
     */
    public static void sendEmail(String toAddress, String subject, String content ,String attachmentPath,String attachmentName) throws Exception, MessagingException {
        Log.i("name","name="+subject);
        Log.i("content", content);
        String host = "smtp.163.com";
        String address = "logfeedback@163.com";
        String from = "logfeedback@163.com";
        String password = "LogFdbk2016zf";// 密码
        if ("".equals(toAddress) || toAddress == null) {
            toAddress = "logfeedback@163.com";
        }
        String port = "25";
        SendEmail(host, address, from, password, toAddress, port, subject, content,attachmentPath,attachmentName);
    }

    /**
     * 邮件发送程序
     *
     * @param host
     *            邮件服务器 如:smtp.qq.com
     * @param address
     *            发送邮件的地址 如:878458730@qq.com
     * @param from
     *            来自: wsx2miao@qq.com/也就是发件人地址
     * @param password
     *            您的邮箱密码
     * @param to
     *            接收人
     * @param port
     *            端口(QQ:25/sina:25/163:25)
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     * @param attachmentPath
     *            附件路径
     * @param attachmentName
     *            附件名称
     * @throws Exception
     */
    public static void SendEmail(String host, String address, String from, String password, String to, String port, String subject, String content,String attachmentPath,String attachmentName) throws Exception {
        Multipart multiPart;
        String finalString = "";
        //附件地址
        // String affix="/mnt/sdcard/oppo.mp4";
        // String affixName="oppo.mp4";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", address);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");

        Log.i("Check", "done pops");
        Session session = Session.getDefaultInstance(props, null);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setDataHandler(handler);
        Log.i("Check", "done sessions");

        multiPart = new MimeMultipart();
        //添加附件
        BodyPart messageBodyPart= new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentPath);
        messageBodyPart.setDataHandler(new DataHandler(source));

        //添加接收人地址to代表接收人地址
        InternetAddress  toAddress = new InternetAddress(to);
        messageBodyPart.setFileName(attachmentName);
        multiPart.addBodyPart(messageBodyPart);

        message.addRecipient(Message.RecipientType.TO, toAddress);
        Log.i("Check", "added recipient");
        message.setSubject(subject);
        // message.setContent(multiPart);
        message.setText(content);

        //将multipart对象放到message中
        message.setContent(multiPart);
        //保存邮件
        message.saveChanges();
        Log.i("check", "transport");
        Transport transport = session.getTransport("smtp");
        Log.i("check", "connecting");
        transport.connect(host, address, password);
        Log.i("check", "wana send");
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        Log.i("check", "sent");
    }
}
public class CrashHandler implements Thread.UncaughtExceptionHandler {}

//系统默认的UncaughtException处理类
private Thread.UncaughtExceptionHandler mDefaultHandler;
//CrashHandler实例
private static CrashHandler INSTANCE = new CrashHandler();
//程序的Context对象
private Context mContext;
//用来存储设备信息和异常信息
private Map<String, String> infos = new HashMap<String, String>();

//用于格式化日期,作为日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

  private CrashHandler(){
 }
//调用
  public static CrashHandler getInstance(){
        return INSTANCE;
 }
  public void init(Context context){
        mContext=context;
        //获取系统默认的UncaughtException处理器
        mDefaultHandler=Thread.getDefaultUncaughtExceptionHandler();
        //设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
    
 @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {           
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error : ", e);
            }
            //退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }
private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
        new Thread() {
            @SuppressLint("ShowToast")
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.",Toast.LENGTH_SHORT);
                Looper.loop();
            }
        }.start();
        //保存日志文件
        final String logFileName = saveCrashInfo2File(ex);
        return true;
    }

    private String saveCrashInfo2File(Throwable ex) {

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        try {
            long timestamp = System.currentTimeMillis();
            String time = formatter.format(new Date());
            String fileName = "crash-" + time + "-" + timestamp + ".log";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String path = "/sdcard/crash/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName);
                fos.write(sb.toString().getBytes());
                fos.close();
            }
            return fileName;
        } catch (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        }
        return null;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment