使用Java Mail API发送邮件,抛出认证错误553 authentication is required. 解决办法

转载原文:https://blog.csdn.net/sun2015_07_24/article/details/52074898

在使用Java Mail API的过程中,抛出553 authentication is required,163 smtp4...异常,究其原因应该是在设置Session时,并未设置auth的值,在代码中添加如下代码块:

    String host = "smtp.163.com";
    // 获取系统属性对象
    Properties properties = System.getProperties();
    // 设置邮件服务器以及授权
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.auth", "true");
    Authentication authentication = new Authentication("username", "password");
    // 获取session对象
    Session mailSession = Session.getDefaultInstance(properties, authentication);

代码中的Authentication类由自己创建,集成javax.mail中的Authenticator即可,如下:

package com.runoob.main;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class Authentication extends Authenticator {
    private String username = null;
    private String password = null;

    public Authentication() {

    }

    public Authentication(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
}

再次执行,即可正常发送邮件。

你可能感兴趣的:(Java)