我正在尝试使用Gmail作为SMTP服务器发送Java电子邮件。但我在标题中得到了例外。我在StackOverflow上发现了这个讨论: javax.mail.AuthenticationFailedException is thrown while sending email in java
但它没有解决问题,我为较低安全性的应用启用了Gmail选项。
这是我的代码:
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);
}
}
这里是我对JNDI资源的context.xml:
<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"
/>
用户/密送是正确的。我尝试使用465和587作为端口。我的代码出了什么问题?