加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

javax.mail.AuthenticationFailedException:连接失败,没有指定

发布时间:2020-12-14 16:27:25 所属栏目:Java 来源:网络整理
导读:此程序尝试发送电子邮件但抛出运行时异常: javax.mail.AuthenticationFailedException: failed to connect,no password specified? 当我提供正确的用户名和密码进行身份验证时,为什么会收到此异常? 发件人和收件人都有g-mail帐户.发件人和收件人都有g-mail
此程序尝试发送电子邮件但抛出运行时异常:
javax.mail.AuthenticationFailedException: failed to connect,no password specified?

当我提供正确的用户名和密码进行身份验证时,为什么会收到此异常?

发件人和收件人都有g-mail帐户.发件人和收件人都有g-mail帐户.发件人已禁用两步验证过程.

这是代码:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

class tester {
    public static void main(String args[]) {
        Properties props = new Properties();
        props.put("mail.smtp.host","smtp.gmail.com");
        props.put("mail.stmp.user","username");

        //To use TLS
        props.put("mail.smtp.auth","true"); 
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.password","password");
        //To use SSL
        props.put("mail.smtp.socketFactory.port","465");
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth","true");
        props.put("mail.smtp.port","465");


        Session session  = Session.getDefaultInstance( props,null);
        String to = "me@gmail.com";
        String from = "from@gmail.com";
        String subject = "Testing...";
        Message msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(from));
            msg.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
            msg.setSubject(subject);
            msg.setText("Working fine..!");
            Transport transport = session.getTransport("smtp");
            transport.connect("smtp.gmail.com",465,"username","password");
            transport.send(msg);
            System.out.println("fine!!");
        }
        catch(Exception exc) {
            System.out.println(exc);
        }
    }
}

即使提供密码,我也得到例外.为什么不认证?

解决方法

尝试创建一个javax.mail.Authenticator对象,并将该属性对象发送到Session对象.

Authenticator
编辑:

您可以修改此接受用户名和密码,您可以将它们存储在那里,或者您想要的地方.

public class SmtpAuthenticator extends Authenticator {
public SmtpAuthenticator() {

    super();
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
 String username = "user";
 String password = "password";
    if ((username != null) && (username.length() > 0) && (password != null) 
      && (password.length   () > 0)) {

        return new PasswordAuthentication(username,password);
    }

    return null;
}

在您发送电子邮件的课程中:

SmtpAuthenticator authentication = new SmtpAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
                    .getDefaultInstance(emailProperties,authenticator));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读