1

我正在尝试编写一种基于参数发送电子邮件的方法,它完全可以在 CentOS 和 OSX 上运行。但是,该方法不能在 Windows(即使在 Windows 上重新编译)以及其他一些 Linux 操作系统上正常工作——它会抛出一个 MessagingException。有没有人知道如何解决这个问题以在 Windows 上工作?谢谢!

private static void sendEmail(String towhom, String subject, String body) {
  String host = "smtp.gmail.com", from = "myemail", pass = "mypassword";
  Properties props = System.getProperties();
  Scanner scan = new Scanner(System.in);

  try {
     props.put("mail.smtp.starttls.enable", "true");
     props.put("mail.smtp.host", host);
     props.put("mail.smtp.user", from);
     props.put("mail.smtp.password", pass);
     props.put("mail.smtp.port", "587");
     props.put("mail.smtp.auth", "true");

     Session session = Session.getDefaultInstance(props, null);
     MimeMessage message = new MimeMessage(session);
     message.setFrom(new InternetAddress(from));

     InternetAddress toAddress = new InternetAddress(towhom);

     message.addRecipient(Message.RecipientType.TO, toAddress);
     message.setSubject(subject);
     message.setText(body);

     Transport transport = session.getTransport("smtp");
     transport.connect(host, from, pass);
     transport.sendMessage(message, message.getAllRecipients());
     transport.close();
  }
  catch(AddressException e) {
     System.out.println("Invalid Email Address.");
  }
  catch(MessagingException e) {
     System.out.print("\nInvalid Email Address, please reenter it: ");
     sendEmail(scan.nextLine(), subject, body);
  }
}
4

2 回答 2

4

So yes Avast Antivirus was causing the exception to be thrown when I was trying to send the mail. If anyone else has this problem who finds this page:

Open up Avast and click on the Security tab. Then click on the AntiVirus tab on the left. Under that, click Mail Shield and go to the settings. Untick "Scan outbound mail (SMTP)" and it will work like a charm.

于 2013-07-04T03:00:07.003 回答
2

您的代码没有问题。这看起来不错的样子。

根据JavaMail FAQ 的. 以下可能是问题所在 -

  • 有防火墙或防病毒程序拦截了您的请求。
  • 您的 JDK 安装出现问题,无法找到受信任的证书颁发机构的证书。
  • 您在覆盖 JDK 的受信任证书颁发机构列表的应用程序服务器中运行。

如果禁用防火墙和/或防病毒软件不能解决问题,那么您可以尝试重新安装 JDK 并进行测试。

于 2013-07-04T02:25:54.587 回答