使用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);
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值