java发送163邮件554、553、535状态码

前言:复习java基础的时候,突然想着自己刚申请的Gmail邮箱,就想到写个发送邮件的程序,用的163邮箱,结果坑爹的反垃圾机制把我折腾死了,网上也有各种解决方法,我就总结我所遇到的,希望给后来者一点帮助,不浪费时间,先解释各个状态码。

1、状态码553:

Caused by: com.sun.mail.smtp.SMTPSenderFailedException: 553 Mail from must equal authorized user
  • 原因: 这是由于发件人的邮箱账号和后面连接登陆的账号和密码必须要一致(不要将发件人邮箱填写成收件人邮箱了);

  • 下面是官方给出553的其它解释

    java发送163邮件554、553、535状态码_第1张图片

2、状态码554

  • 给出官方的解释,我在邮箱中将本机ip加入后得以解决。

    java发送163邮件554、553、535状态码_第2张图片

3、状态码535

javax.mail.AuthenticationFailedException: 535 Error: authentication failed
  • 这是由于163的POP3/SMTP/IMAP服务没有开启,需要登陆163邮箱进行操作。

  • 这个写得挺详细的:http://clovemfong.blog.51cto.com/3297559/1702105

4、贴代码

package com.fang.test;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailTest {

    public static void main(String[] args) {
        //发件人电子邮箱
        String from = "[email protected]";
        //收件人电子邮箱
        String to = "[email protected]";

        //也可以以此来获得系统属性:Properties properties = System.getProperties();
        Properties properties = new Properties();  
        // 设置邮件服务器主机名  
        properties.setProperty("mail.host", "smtp.163.com"); 

        //这行代码是我在遇到554返回码时加上的,同时也将发送内容中的“test,测试”等关键字去掉了
        //在163邮箱的白名单也设置了本地ip,后来注释掉这行代码发送消息也没有报错了
        //properties.setProperty("mail.smtp.localhost", "127.0.0.1");

        // 发送邮件协议名称  
        properties.setProperty("mail.transport.protocol", "smtp"); 
        //这行代码网上有说必须要将后面设为“true”,经过亲测,后面改为“false”也不会报错
        properties.setProperty("mail.smtp.auth", "true"); 
        //debug时使用,可以看到发送的状态,十分有用
        properties.setProperty("mail.debug", "true");  
        //获取默认的session
        Session session = Session.getDefaultInstance(properties);

        try {
            //创建一个默认的Message对象
            Message message = new MimeMessage(session);
            //设置发件人信息
            message.setFrom(new InternetAddress(from));
            //设置邮件的标题
            message.setSubject("新势!");
            //设置邮件内容
            message.setText("收到请回复");
            Transport transport = session.getTransport();  
            // 连接邮件服务器  
            transport.connect(from, "客户端授权密码"); 
            //发送消息,多个收件人后面地址填上多个
            transport.sendMessage(message,new Address[]{new InternetAddress(to)});
            transport.close();  
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            System.out.println("Error: unable to send message....");
            mex.printStackTrace();       
        }
    }
}

你可能感兴趣的:(java,邮件,java)