I’m having trouble with the JavaMail API and Gmail. When I try to send an email, an authentication error occurs. I am certain that the username and password I am using are correct, and I am using an older Gmail account that might take additional time to set up properly. The error being received is: “535-5.7.1 Username and Password not accepted.”
Below is a revised version of my code:
public class EmailDispatcher {
private static final String HOST = "smtp.gmail.com";
private static final String PORT = "465";
public void dispatchEmail() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", HOST);
properties.put("mail.smtp.port", PORT);
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "userpass");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Email Test");
message.setText("This message is a demonstration of a test email.");
Transport.send(message);
} catch (MessagingException exception) {
exception.printStackTrace();
}
}
}
Has anyone encountered this error before and can suggest what might be causing it?