【发布时间】:2013-03-13 22:04:09
【问题描述】:
这段代码有什么问题?不知何故,它进入了Transport.send(message); 行的无限循环,没有错误消息,没有异常,只是可能无限循环(我不知道,因为我等待的时间不超过 5-10 分钟)
final String username = "<mail_name>";
final String password = "<password>";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("<mail_from>@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("<mail_to>@gmail.com"));
message.setSubject("Test Subject");
message.setText("Test");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
【问题讨论】:
-
我建议在
MessagingException之后添加一个catch (Exception e){},以查看是否会引发其他类型的异常。还要添加一个finally块。您还可以添加log4j.xml并将javax.mail类设置为DEBUG,看看还会发生什么。 -
很好的提示,谢谢!会测试它
-
不幸的是仍在 Transport.send(message) 线上等待...有人可以验证此代码的正确性吗?
标签: java smtp jakarta-mail