我正在尝试通过我的 gmail 帐户使用 JavaMail API 作为电子邮件发送,但我收到了 javax.mail.MessagingException 异常
编码 :
public static Result sendMail() {
Map < String, String[] > values = request().body().asFormUrlEncoded();
String toAddresses = values.get("toaddrs")[0];
String subject = values.get("subject")[0];
String body = values.get("body")[0];
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
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, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("samplemail@gmail.com", "samplepass");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("samplemail@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
return ok("sent");
} catch (MessagingException e) {
return ok("Error in sending email");
}
}
在调试时,我在服务类中结束
引发异常:javax.mail.MessagingException: Host, username, and password must be specified.