【发布时间】:2017-07-20 19:40:31
【问题描述】:
在会话对象(PasswordAuthentication ) 中的以下代码中,我们必须提供什么用户名和密码才能发送邮件?发件人的用户名密码或收件人的凭据?
我真的很困惑,我正在使用 java Mail 发送邮件
public void sendMail(String email,String token)
{
// Recipient's email ID needs to be mentioned.
String to = email;
// Sender's email ID needs to be mentioned
// Assuming you are sending email through relay.jangosmtp.net
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress("Issme-Customer-Service"));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Email Verification Of issme Account");
message.setContent(
"<h2>Email Verification </h2>" +
"<h3> Please goto the following URL to verify your ISSME account\n </h3> " +
token , "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
【问题讨论】:
-
为什么会是接收方的凭据?这是发件人的用户名和密码,就像您在邮件客户端中设置的一样。
-
如果这是一个 Web 应用程序,最好在应用程序服务器中设置一个 JavaMail 会话。与外部服务的连接是一个部署环境问题,它们的参数不应被硬编码。
-
您需要设置可以向 SMTP 服务器(发件人)进行身份验证的凭据
标签: java session authentication jakarta-mail