我正在尝试编写一种基于参数发送电子邮件的方法,它完全可以在 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);
}
}