I am trying to send an email in Java using Gmail as SMTP server. But I got the exception in the Title. I found this discussion on StackOverflow: javax.mail.AuthenticationFailedException is thrown while sending email in java
But it didn't solve the issue, I have Gmail option enabled for less security app.
Here my Code:
public void send(EmailMessage msg) throws MailException {
try {
Session session = (Session) ServiceLocator.getInstance().getService(MAIL_JNDI_NAME);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sasadangelo@gmail.com", "Bazaar Support"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(msg.getTo(), false));
message.setDataHandler(new DataHandler(new ByteArrayDataSource(msg.getBody(), "text/html")));
message.setHeader("X-Mailer", "NeuroSpeech Mailer");
message.setSentDate(new Date());
message.setSubject(msg.getSubject());
Transport.send(message);
} catch(NamingException exception) {
throw new MailException(IErrorCodes.ERR_JNDI_ACCESS);
} catch(MessagingException message) {
throw new MailException(IErrorCodes.ERR_UNABLE_SEND_EMAIL);
} catch(UnsupportedEncodingException message) {
throw new MailException(IErrorCodes.ERR_UNABLE_SEND_EMAIL);
}
}
and here my context.xml for JNDI resource:
<Resource name="mail/Session" auth="Container"
type="javax.mail.Session"
username="sasadangelo@gmail.com"
password="********"
mail.debug="true"
mail.transport.protocol="smtp"
mail.smtp.host= "smtp.gmail.com"
mail.smtp.auth= "true"
mail.smtp.port= "587"
mail.smtp.starttls.enable="true"
description="Global E-Mail Resource"
/>
User/Pwd are correct. I tried to use 465 and 587 as port. What's wrong with my code?