码迷,mamicode.com
首页 > 移动开发 > 详细

Android发送邮件

时间:2015-08-31 23:41:40      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

项目中有些关键日志需要从客户手中拿到,为了方便的收集日志在客户端中加入邮件发送功能(虽然使用分享功能也能发送邮件,前提需要客户登录手机的邮箱才行,比较麻烦,而且还进入页面,用户体验不太好)。

主要实现了发送邮件,抄送,发送附件功能

先看一下效果图:

技术分享

涉及到3个jar以及封装的接口

JEmailHelper.java
package jwzhangjie.com.javaemail;

import android.os.AsyncTask;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
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;

/**
 * Created by zhangjie on 15/8/31.
 */
public class JEmailHelper {

    private int port = 553;  //smtp协议使用的端口
    private String host = "smtp.163.com"; // 发件人邮件服务器
    private String user = "*******@163.com";   // 使用者账号
    private String password = "********"; //使用者密码

    private List<String> emailTos;
    private List<String> emailCCs;
    private String subject;
    private String body;
    private List<String> paths;

    enum SendStatus {
        SENDING, UNDO, SENDOK, SENDFAIL
    }

    ;

    private SendStatus sendStatus;

    public interface JieEmailInfterface {
        void startSend();

        void SendStatus(SendStatus sendStatus);
    }

    private JieEmailInfterface jieEmailInfterface;

    public void setJieEmailInfterface(JieEmailInfterface jieEmailInfterface) {
        this.jieEmailInfterface = jieEmailInfterface;
    }


    public JEmailHelper() {
        sendStatus = SendStatus.UNDO;
    }

    //构造发送邮件帐户的服务器,端口,帐户,密码
    public JEmailHelper(String host, int port, String user, String password) {
        this.port = port;
        this.user = user;
        this.password = password;
        this.host = host;
        sendStatus = SendStatus.UNDO;
    }

    /**
     * @param emailTos 主要接收人的电子邮箱列表
     * @param emailCCs 抄送人的电子邮箱列表
     * @param subject  邮件标题
     * @param body     正文内容
     * @param paths    发送的附件路径集合
     */
    public void setParams(List<String> emailTos, List<String> emailCCs, String subject, String body,
                          List<String> paths) {
        this.emailTos = emailTos;
        this.emailCCs = emailCCs;
        this.subject = subject;
        this.body = body;
        this.paths = paths;
    }

    public void sendEmail() {
        new JieAsynTask().execute();
    }

    private void sendEmailBg() throws Exception {
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");//true一定要加引号
        properties.put("mail.transport.protocol", "smtp");

        JieAuthenticator jieAuth = new JieAuthenticator(user, password);

        Session session = Session.getInstance(properties, jieAuth);
        //创建一个消息
        MimeMessage msg = new MimeMessage(session);

        //设置发送人
        msg.setFrom(new InternetAddress(user));

        //设置主要接收人
        if (emailTos != null && !emailTos.isEmpty()) {
            int size = emailTos.size();
            InternetAddress[] addresses = new InternetAddress[size];
            for (int i = 0; i < size; i++) {
                addresses[i] = new InternetAddress(emailTos.get(i));
            }
            msg.setRecipients(Message.RecipientType.TO, addresses);
        }

        //设置抄送人的电子邮件
        if (emailCCs != null && !emailCCs.isEmpty()) {
            int size = emailCCs.size();
            InternetAddress[] addresses = new InternetAddress[size];
            for (int i = 0; i < size; i++) {
                addresses[i] = new InternetAddress(emailCCs.get(i));
            }
            msg.setRecipients(Message.RecipientType.CC, addresses);
        }

        msg.setSubject(subject);

        //创建一个消息体
        MimeBodyPart msgBodyPart = new MimeBodyPart();
        msgBodyPart.setText(body);

        //创建Multipart增加其他的parts
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(msgBodyPart);

        //创建文件附件
        for (String path : paths) {
            MimeBodyPart fileBodyPart = new MimeBodyPart();
            fileBodyPart.attachFile(path);
            mp.addBodyPart(fileBodyPart);
        }

        //增加Multipart到消息体中
        msg.setContent(mp);
        //设置日期
        msg.setSentDate(new Date());
        //设置附件格式
        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);
        //发送消息
        Transport.send(msg);
    }

    class JieAuthenticator extends Authenticator {
        private String strUser;
        private String strPwd;

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


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

    class JieAsynTask extends AsyncTask<Void, Void, SendStatus> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (jieEmailInfterface != null) {
                jieEmailInfterface.startSend();
            }
        }

        @Override
        protected void onPostExecute(SendStatus result) {
            super.onPostExecute(result);
            if (jieEmailInfterface != null) {
                jieEmailInfterface.SendStatus(result);
            }
            sendStatus = SendStatus.UNDO;
        }

        @Override
        protected SendStatus doInBackground(Void... params) {
            try {
                sendStatus = SendStatus.SENDING;
                sendEmailBg();
                sendStatus = SendStatus.SENDOK;
            } catch (Exception e) {
                e.printStackTrace();
                sendStatus = SendStatus.SENDFAIL;
            }
            return sendStatus;
        }
    }
}

package jwzhangjie.com.javaemail;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class JavaEmailActivity extends Activity {

    JEmailHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_java_email);
        helper = new JEmailHelper();
    }

    public void sendMail(View view) {

        List<String> files = new ArrayList<String>();
        files.add("/mnt/sdcard/test.txt");
        List<String> toEmail = new ArrayList<String>();
        toEmail.add("jwzhangjie@163.com");
        List<String> ccEmail = new ArrayList<String>();
        ccEmail.add("1067*****@qq.com");
        ccEmail.add("352****@qq.com");
        helper.setParams(toEmail, ccEmail, "Android发送测试邮件", "Dear All:这是一封测试邮件!", files);
        helper.setJieEmailInfterface(new JEmailHelper.JieEmailInfterface() {
            @Override
            public void startSend() {
                showInfo("开始发送邮件");
            }

            @Override
            public void SendStatus(JEmailHelper.SendStatus sendStatus) {
                switch (sendStatus) {
                    case SENDOK:
                        showInfo("发送邮件成功");
                        break;
                    case SENDFAIL:
                        showInfo("发送邮件失败");
                        break;
                    case SENDING:
                        showInfo("邮件正在发送中,请稍后重试");
                        break;
                }
            }
        });
        helper.sendEmail();
    }

    public void showInfo(String msg){
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }
}
三个jar的地址:
http://pan.baidu.com/s/1bnbi7zp

版权声明:本文为博主原创文章,未经博主允许不得转载。

Android发送邮件

标签:

原文地址:http://blog.csdn.net/jwzhangjie/article/details/48142133

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!