All Things Techie With Huge, Unstructured, Intuitive Leaps

Javamail Won't Work: AuthenticationFailedException



Everyone knows how to use JavaMail API and the javamail.jar.  I wrote a class to send emails:  The code looked like this:

public synchronized static boolean sendMail() {
Properties props = new Properties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", smtp_host);
props.put("mail.smtp.port", use_port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.auth.mechanisms", "PLAIN");
props.put("mail.smtp.debug", "false");
props.put("mail.smtp.socketFactory.port", use_port);
props.put("mail.smtp.socketFactory.class", socketFactoryClass);
props.put("mail.smtp.socketFactory.fallback", "false");

try {
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
MimeMessage msg = new MimeMessage(session);
msg.setText(msg_text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
to_addr));
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(smtp_host, userName, acct_pwd);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
return false;
}
}

Easy, peasy piece of cake - right? Nope!

It kept throwing an exception: java - javax.mail.AuthenticationFailedException: 535 5.0.0 Authentication Failed

I tore my hair out over this one.  I couldn't figure it out. And weirdly enough, the code worked on a Windoze server but not on a Linux server.  What do to? Go back to first principles.

The fix was a simple line.  I added this line to the properties:

props.put("mail.smtp.auth", "true");

and the thing worked on Linux. And it still worked on Windoze.

Hope this helps someone.

No comments:

Post a Comment