我正在嘗試編寫一種基於參數發送電子郵件的方法,它完全適用於CentOS和OSX。但是,該方法在Windows上無法正常工作(即使在Windows上重新編譯時)以及其他一些Linux操作系統 - 它會引發MessagingException。有沒有人有任何想法,我可以如何解決這個在Windows上工作?謝謝!在某些機器上拋出MessagingException,但在其他機器上工作正常
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);
}
}
你可以添加堆棧跟蹤?另外,你可以從你的linux終端上telnet smtp.gmail.com 587嗎? – JHS
'MessagingException'catch塊中的'e.printStackTrace();'。 – JHS
這是太長,只貼:http://pastebin.com/02xP4171 –