I have what appears to be very simple code to try and send an email from my Java app using my Gmail account. When I run it, it crashes with the exception javax.mail.AuthenticationFailedException. Here is the code:
// Recipient's email ID needs to be mentioned.
String to = "[email protected]";
// Sender's email ID needs to be mentioned
String from = "[email protected]";
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("[email protected]","password");
}
});
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("Test Subject");
// Now set the actual message
message.setText("this is a test");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
System.out.println (mex) ;
mex.printStackTrace();
}