问题:在使用Java Mail API时,还有其他方法可以验证凭据 之前发送电子邮件吗?
简介
我的目标是将发送电子邮件分为两步:
登录(如果用户名或密码不匹配,用户将收到相应的消息)
发送电子邮件
目前我正在从这段代码中实现它:
...
// 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);
...
结论: 我的工作做得很好,但我很好奇是否有其他方法可以达到同样的目标?
答案 0 :(得分:1)
您已经在代码中找到了答案。 connect方法使用您的用户名和密码登录,如果失败则抛出异常,sendMessage消息发送消息。这真的不明显吗?
答案 1 :(得分:1)
这种方法比我的方法更方便,原因有两个:
send(Message msg)
,我们之前无法使用这次我们需要在getInstance()
方法
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);