我正在尝试将电子邮件发送到我为动态提醒设置的电子邮件帐户(gmail),当我不在家使用javamail时,但是我使用的所有示例代码都正确编译,但是当我发错时给我一个错误尝试运行代码(javax.mail.AuthenticationFailedException)。这里我提供了一段我目前正在使用的代码。
public static void main(String[] args) {
final String username = "username@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.com"));
message.setSubject("Sample Subject");
message.setText("Sample body");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}