• 保存到桌面  加入收藏  设为首页
Java

Java-发送邮件-使用JavaMail发送邮件-支持多收件人-添加附件

时间:2017-09-19 16:15:31   作者:江节胜   来源:胜行天下   阅读:419   评论:0
package com.jiangjiesheng.utils;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
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;
import android.util.Log;
/**
 * 类说明 :使用JavaMail发送邮件,只需要mail.jar、additionnal.jar和activation.jar。
 * 还可以使用Apache发送邮箱.
 
 * @author 江节胜 E-mail:dev@jiangjiesheng.cn
 * @version 创建时间:2017-4-28 下午1:44:40
 */
public class EmailSender {
    public final static String TAG = "EmailSender";
    public final static int SEND_RESULT_SUCCESSED = 0X777;
    public final static int SEND_RESULT_FAILED = 0X888;
    public final static int SEND_RESULT_EXCEPTION = 0X999;
    /********************************************
     ********** 用于发送状态的回调,直接复制代码*************
     ******************************************** 
     */
    // EmailSender.sendeMail("xxxxxxxxxxxxxx@qq.com", "xxxxxxxxxxxxxxx",
    // "xxxxxxxxxxxx@qq.com", "dev@jiangjiesheng.cn", "建安通程序Crash日志--",
    // "body", null, new EmailSenderListener() {
    //
    // @Override
    // public void emailSendResult(int resultCode,
    // String resultMsg, String attachmentPath, Exception e) {
    // switch (resultCode) {
    // case EmailSender.SEND_RESULT_SUCCESSED:// 成功
    // Log.e(EmailSender.TAG, resultMsg + ",附件地址:"
    // + (attachmentPath != null ? attachmentPath
    // : "null"));
    //
    // break;
    // case EmailSender.SEND_RESULT_FAILED:// 失败
    // Log.e(EmailSender.TAG, resultMsg + ",附件地址:"
    // + (attachmentPath != null ? attachmentPath
    // : "null"));
    // break;
    // case EmailSender.SEND_RESULT_EXCEPTION:// 异常
    // Log.e(EmailSender.TAG, resultMsg+",附件地址:"+(attachmentPath != null ?
    // attachmentPath
    // : "null")+ ",异常:" + e.getMessage());
    // break;
    //
    // default:
    // break;
    // }
    // }
    // });// 发邮件的话,说明当前软件运行环境
    /**
     * 方法说明: 如果使用非腾讯邮箱,需要修改_host(smtp server 发送方邮件服务器)。
     * 需要发件人开启POP3/STMP、IMAP/SMTP ,收件人是否需要开启未测试。 最好开启子线程:Class Xxx implements
     * Runnable ,new Thread(new Xxx()).start() android.os.Process.killProcess
     * (android.os.Process.myPid());//这个可能是关闭整个应用了,使用时慎重,视需求。 需要的把账号信息封装一下。
     
     * @author 江节胜 ,E-mail:dev@jiangjiesheng.cn
     * @version 创建时间:2017-4-28 下午1:21:32
     
     * @param senderAccout
     *            发件人账号 xxx@qq.com 
     * @param senderpwd
     *            现在应该都是授权码 XXXXXXXXXX
     * @param sendereMail
     *            发件人邮件:最好跟senderAccout相同,否则不能发送
     * @param receivers
     *            多邮箱使用逗号连接
     * @param subject
     *            主题
     * @param body
     *            邮件正文
     * @param attachmentPath
     *            邮件附件 无附件传null
     * @return true: 邮件发送完成 false:邮件发送过程出错
     
     */
    public static void sendeMail(final String senderAccout,
                final String senderPwd, final String sendereMail,
                final String receivereMails, final String subject,
                final String body, final String attachmentPath,
                final EmailSenderListener emailSenderListener) {
        new Thread(new Runnable() {
            @Override
                        public void run() {
                MyMail m = new MyMail(senderAccout, senderPwd);
                m.set_debuggable(false);
                m.set_host("smtp.qq.com");
                // default smtp server 发送方邮件服务器
                m.set_port("465");
                // default smtp port
                m.set_sport("465");
                // default socketfactory por
                String[] toArr = { receivereMails };
                m.set_to(toArr);
                m.set_from(sendereMail);
                m.set_subject(subject);
                m.setBody(body);
                try {
                    if (attachmentPath != null  !attachmentPath.isEmpty()) {
                        File f = new File(attachmentPath);
                        if (f.isFile()  f.canRead()) {
                            m.addAttachment(attachmentPath);
                        else {
                            Log.e(TAG, "附件非文件路径或者附件不可读");
                        }
                    }
                    if (m.send()) {
                        Log.e(TAG, "邮件发送成功");
                        if (emailSenderListener != null) {
                            emailSenderListener.emailSendResult(
                                                                SEND_RESULT_SUCCESSED,
                                                                "Email send success", attachmentPath, null);
                        }
                    else {
                        Log.e(TAG, "邮件发送失败");
                        if (emailSenderListener != null) {
                            emailSenderListener.emailSendResult(
                                                                SEND_RESULT_FAILED, "Email send failed",
                                                                attachmentPath, null);
                        }
                    }
                }
                catch (Exception e) {
                    Log.e(TAG, "邮件发送异常:" + e.getMessage());
                    if (emailSenderListener != null) {
                        emailSenderListener
                                                        .emailSendResult(
                                                                SEND_RESULT_EXCEPTION,
                                                                "An exception occurred when the email was sending",
                                                                attachmentPath, e);
                    }
                }
            }
        }
        ).start();
    }
    public interface EmailSenderListener {
        /**
         * 方法说明:发送结果状态
         */
        public void emailSendResult(int resultCode, String resultMsg,
                        String attachmentPath, Exception e);
    }
}
class MyMail extends javax.mail.Authenticator {
    private String _user;
    private String _pass;
    private String[] _to;
    private String _from;
    private String _port;
    private String _sport;
    private String _host;
    private String _subject;
    private String _body;
    private Boolean _auth;
    private Boolean _debuggable;
    private Multipart _multipart;
    public MyMail() {
        // _host = "smtp.qq.com"; // default smtp server 发送方邮件服务器
        // _port = "465"; // default smtp port
        // _sport = "465"; // default socketfactory port
        _user = "";
        // username
        _pass = "";
        // password
        _from = "";
        // email sent from
        _subject = "";
        // email subject
        _body = "";
        // email body
        _debuggable = false;
        // debug mode on or off - default off
        _auth = true;
        // smtp authentication - default on
        _multipart = new MimeMultipart();
        // There is something wrong with
        // MailCap, javamail can not find a
        // handler for the multipart/mixed
        // part, so this bit needs to be
        // added.
        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);
    }
    public String get_user() {
        return _user;
    }
    public void set_user(String _user) {
        this._user = _user;
    }
    public String get_pass() {
        return _pass;
    }
    public void set_pass(String _pass) {
        this._pass = _pass;
    }
    public String[] get_to() {
        return _to;
    }
    public void set_to(String[] _to) {
        this._to = _to;
    }
    public String get_from() {
        return _from;
    }
    public void set_from(String _from) {
        this._from = _from;
    }
    public String get_port() {
        return _port;
    }
    public void set_port(String _port) {
        this._port = _port;
    }
    public String get_sport() {
        return _sport;
    }
    public void set_sport(String _sport) {
        this._sport = _sport;
    }
    public String get_host() {
        return _host;
    }
    public void set_host(String _host) {
        this._host = _host;
    }
    public String get_subject() {
        return _subject;
    }
    public void set_subject(String _subject) {
        this._subject = _subject;
    }
    public String get_body() {
        return _body;
    }
    public void set_body(String _body) {
        this._body = _body;
    }
    public Boolean is_auth() {
        return _auth;
    }
    public void set_auth(Boolean _auth) {
        this._auth = _auth;
    }
    public Boolean is_debuggable() {
        return _debuggable;
    }
    public void set_debuggable(Boolean _debuggable) {
        this._debuggable = _debuggable;
    }
    public Multipart get_multipart() {
        return _multipart;
    }
    public void set_multipart(Multipart _multipart) {
        this._multipart = _multipart;
    }
    public MyMail(String user, String pass) {
        this();
        _user = user;
        _pass = pass;
    }
    public Boolean send() throws Exception {
        Properties props = _setProperties();
        if (!_user.equals("")  !_pass.equals("")  _to.length >
        0
                         !_from.equals("")  !_subject.equals("")
                         !_body.equals("")) {
            Session session = Session.getInstance(props, this);
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(_from));
            InternetAddress[] addressTo = new InternetAddress[_to.length];
            for (int i = 0; i < _to.length; i++) {
                addressTo[i] = new InternetAddress(_to[i]);
            }
            msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
            msg.setSubject(_subject);
            msg.setSentDate(new Date());
            // setup message body BodyPart
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(_body);
            _
            multipart.addBodyPart(messageBodyPart);
            // Put parts in message 
            msg.setContent(_multipart);
            //send email
            Transport.send(msg);
            return true;
        else {
            return false;
        }
    }
    public void addAttachment(String filename) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        String[] zhong = filename.split("/");
        String my_filename = zhong[zhong.length - 1];
        messageBodyPart.setFileName(my_filename);
        _multipart.addBodyPart(messageBodyPart);
    }
    @Override public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(_user, _pass);
    }
    private Properties _setProperties() {
        Properties props = new Properties();
        props.put("mail.smtp.host", _host);
        if (_debuggable) {
            props.put("mail.debug""true");
        }
        if (_auth) {
            props.put("mail.smtp.auth""true");
        }
        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");
        return props;
    }
    // the getters and setters 
    public String getBody() {
        return _body;
    }
    public void setBody(String _body) {
        this._body = _body;
    }
    // more of the getters and setters .. } }

有任何疑问或技术合作都可联系我

微信:767000122 【推荐】

QQ:596957738


标签:Java发送邮件  
相关评论

加我微信 596957738 (QQ同号)加我微信   QQ联系:596957738   地址:江苏省南京市雨花台区

苏公网安备32011402010305号

皖ICP备16019989号

江节胜的Gitee,江节胜的Git地址