Java Mail API凭据验证

时间:2018-04-16 23:58:02

标签: java session gmail javamail transport

问题:在使用Java Mail API时,还有其他方法可以验证凭据 之前发送电子邮件吗?

简介

我的目标是将发送电子邮件分为两步:

  1. 登录(如果用户名或密码不匹配,用户将收到相应的消息)

  2. 发送电子邮件

  3. 目前我正在从这段代码中实现它:

    ...
    // no Authenticator implementation as a parameter 
    Session session = Session.getInstance(Properties props); 
    Transport transport = session.getTransport("smtp");
    
    transport.connect(username, password);
    
    transport.sendMessage(Message msg, Address[] addresses);
    ...
    

    结论: 我的工作做得很好,但我很好奇是否有其他方法可以达到同样的目标?

2 个答案:

答案 0 :(得分:1)

您已经在代码中找到了答案。 connect方法使用您的用户名和密码登录,如果失败则抛出异常,sendMessage消息发送消息。这真的不明显吗?

答案 1 :(得分:1)

在发送电子邮件之前验证凭据的另一种方法

这种方法比我的方法更方便,原因有两个:

  • 我们无需保持传输的实例
  • 要发送电子邮件,我们只需使用传输的静态方法send(Message msg),我们之前无法使用

这次我们需要在getInstance()方法

中传递Authenticator
Session session = Session.getInstance(props, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(“username”, “password”);
    }
}

/*
 * no need to pass protocol to getTransport()
 * no need to pass username and password to connect() 
 * if credentials were incorrect, you would get a corresponding error
 */
session.getTransport().connect();



// no need to use instance, we simply use static method
Transport.send(message);