Android 使用javamail发送邮件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010218170/article/details/83107554

项目需要activation.jar,additionnal.jar,mail.jar 下载三个包

编写邮件发送步骤:

  1. 设置服务器
  2. 添加邮箱认证
  3. 设置认证的Session(重要)
  4. 根据Session获取邮件对象(MimeMessage)
  5. 邮件对象的填充(发件人,收件人,标题,内容和附件)
  6. 邮件的发送

编写代码如下:

/*发送邮件的主要代码*/

Properties properties = System.getProperties();//获取系统属性
properties.put("mail.smtp.host", "smtp.sina.com");//邮箱对于的服务器
properties.put("mail.smtp.auth", "true");//设置需要用户名和密码(客户端授权码)认证
Session session = Session.getDefaultInstance(properties,new Authenticator(){//认证Session
     @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password); //发件人邮件用户名、密码(客户端授权码)
    }
});
session.setDebug(true);//Log输出,方便调试
MimeMessage message = new MimeMessage(session);//根据Session获得邮件对象
try {
    message.setFrom(new InternetAddress(from_email));//添加发件人
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to_email));//添加收件人
    message.setSubject("This is the Subject Line!");//标题
    Multipart multipart = new MimeMultipart();//可以带附件消息对象
    BodyPart messageBodyPart = new MimeBodyPart();//文本消息部分
    messageBodyPart.setText("This is message body");
    multipart.addBodyPart(messageBodyPart);//添加文本消息
    for (int i=0;i<fileList.size();i++) {//fileList是List<File>
        BodyPart fileBodyPart = new MimeBodyPart();//附件部分
        DataSource source = new FileDataSource(fileList.get(i));
        fileBodyPart.setDataHandler(new DataHandler(source));
        fileBodyPart.setFileName(fileList.get(i).getName());
        multipart.addBodyPart(fileBodyPart);//添加附件消息
    }
    message.setContent(multipart);//填充消息
    //解决javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;
    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);
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    
    Transport transport = session.getTransport("smtp");
    transport.addTransportListener(new TransportAdapter() {//邮件发送监听
        @Override
        public void messageDelivered(TransportEvent e) {
            super.messageDelivered(e);
            Log.e("监听邮件发送","邮件发送成功....");
        }

        @Override
        public void messageNotDelivered(TransportEvent e) {
            super.messageNotDelivered(e);
            Log.e("监听邮件发送","邮件发送失败....");
        }

        @Override
        public void messagePartiallyDelivered(TransportEvent e) {
            super.messagePartiallyDelivered(e);
            Log.e("监听邮件发送","邮件发送部分成功....");
        }
    });
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
} catch (MessagingException e) {
    e.printStackTrace();
}

测试邮箱:163邮箱、qq邮箱、139邮箱、sohu邮箱、126邮箱、tom邮箱、新浪邮箱、outlook邮箱、aliyun邮箱

  • aliyun邮箱发送邮件都被系统退回(个人无解)
  • 163邮箱发送邮件基本都有遇到com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 问题(个人无解)
  • Log输出提示发送成功,但是收件人邮箱没有收到(邮件被退回或收件人邮箱不存在)
  • 发送成功,收件箱看不到(在垃圾箱)
  • outlook邮箱注册但未验证发邮件会被系统拦截

163邮箱,遇到问题:

1、com.sun.mail.smtp.SMTPSenderFailedException: 550 User has no permission

//设置客户端授权码并开启POP3/SMTP/IMAP

2、com.sun.mail.smtp.SMTPSendFailedException: 553 authentication is required

//添加
properties.put("mail.smtp.auth", "true");(设置完没有添加用户名和授权码会遇到下面一个问题)

3、javax.mail.AuthenticationFailedException: failed to connect, no password specified?

//设置
session = Session.getInstance(email.properties,new Authenticator(){
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        //发件人邮件用户名、授权码
        return new PasswordAuthentication(userName, password);
    }
});

4、javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed

//发送Multipart消息前添加
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);
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
Transport.send(message);//发送消息

5、java.io.IOException: javax.mail.MessagingException: Empty multipart: multipart/mixed

//添加内容或附件
multipart.addBodyPart(new MimeBodyPart());//自己设置MimeBodyPart

6、com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 163 smtp14,please see http://mail.163.com/help/help_spam_16.htm?ip=125.118.87.97&hostid=smtp14&time=1539868670

//•554 DT:SPM 发送的邮件内容包含了未被许可的信息,或被系统识别为垃圾邮件。请检查是否有用户发送病毒或者垃圾邮件;
//呵呵
//我试了2个qq邮箱,都是这情况。换了个139邮箱,就发送成功了。之后再试其他邮箱(包括139)一直被系统识别为垃圾邮件

qq邮箱,遇到问题(已经设置客户端授权码并开启POP3/SMTP/IMAP)

1、com.sun.mail.smtp.SMTPSendFailedException: 503 Error: need EHLO and AUTH first !

//添加
properties.put("mail.smtp.auth", "true");
//设置
session = Session.getInstance(email.properties,new Authenticator(){
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        //发件人邮件用户名、授权码
        return new PasswordAuthentication(userName, password);
    }
});

2、javax.mail.NoSuchProviderException: Invalid protocol: null(设置addTransportListener监听邮件发送状况时出现)

//设置
Transport transport = session.getTransport("smtp");

搜狐邮箱,遇到问题

1、javax.mail.AuthenticationFailedException: 535 5.7.0 smtp is disabled

//开启POP3/SMTP/IMAP

126邮箱,遇到问题

1、javax.mail.AuthenticationFailedException: 550 Óû§ÎÞȨµÇ½

//开启POP3/SMTP/IMAP,并设置客户端授权码

2、javax.mail.AuthenticationFailedException: 535 Error: authentication failed

//认证的用户名或客户授权码输入错误

新浪邮箱,遇到问题

1、javax.mail.AuthenticationFailedException: 535 5.7.12 SMTP access disabled

//客户端pop/imap/smtp,设置服务开启

outlook邮箱,遇到问题

1、com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [HK0PR01CA0005.apcprd01.prod.exchangelabs.com] 

properties.put("mail.smtp.starttls.enable","true");

2、com.sun.mail.smtp.SMTPSendFailedException: 554 5.2.0 STOREDRV.Submission.Exception:OutboundSpamException; Failed to process message due to a permanent exception with message WASCL UserAction verdict is not None. Actual verdict is HipSend, ShowTierUpgrade. OutboundSpamException: WASCL UserAction verdict is not None.

//发件人邮箱未验证,被认为垃圾邮件发送者(验证后就可以了)

猜你喜欢

转载自blog.csdn.net/u010218170/article/details/83107554
今日推荐