我已经解决了这个问题好几天了。我访问了论坛,我尝试了不同的调整,但没有解决方案。
请告诉我为什么我的示例javaMail代码无法从任何Gmail帐户发送邮件?适用于SSL和TLS。
以下是我的代码段;
public class EmailUtility {
public static String USERNAME = "???@gmail.com";
public static String PASSWORD = "???";
public static String HOST = "smtp.gmail.com";
public static String PORT = "587";
public static void sendEmail(String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", HOST );
properties.put("mail.smtp.port", PORT );
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
Authenticator auth = new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USERNAME , PASSWORD );
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(USERNAME ));
InternetAddress[] toAddresses = {new InternetAddress(toAddress)};
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
// sends the e-mail
Transport.send(msg);
}
}