它可以在 Windows 机器上运行,但会抛出:com.sun.mail.util.MailConnectException: Couldn't connect to host, port: wo35.wiroos.host, 25; 超时-1;尝试在 Ubuntu 中发送电子邮件时。
我在 Windows 和 ubuntu 服务器中都使用 Tomcat。
我正在使用 javax.mail 版本 1.5.5
不工作的代码:
String host = "wo35.wiroos.host";
public void sendEmail(String emailBody, String to) throws AddressException, MessagingException, UnsupportedEncodingException {
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user, "From"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject");
message.setText(emailBody);
//send the message
Transport.send(message);
System.out.println("Ok");
}