我正在尝试编写一个简单的 Java 程序来使用 JavaMail API 从我的 hotmail 帐户发送电子邮件。这是我的代码:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class HotMailSend {
public static void main(String args[])
{
final String username = HOTMAIL.username;
final String password = HOTMAIL.password;
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.host", "smtp.live.com");
props.setProperty("mail.smtp.port", "587");
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(HOTMAIL.username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(GMAIL.username));
message.setSubject("Testing Subject");
message.setText("Hey Buddy..!!!,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
这是我得到的错误:
线程“main”中的异常 java.lang.RuntimeException: javax.mail.MessagingException: Can't send command to SMTP host; 嵌套异常是:java.net.SocketException:连接由远程主机在 HotMailSend.main(HotMailSend.java:45) 引起:javax.mail.MessagingException:无法向 SMTP 主机发送命令;嵌套异常是: java.net.SocketException: Connection closed by remote host at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2163) at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java :2150) 在 com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1220) 在 javax.mail.Transport.send0(Transport.java:197) 在 javax.mail.Transport.send(Transport.java: 124) 在 HotMailSend.main(HotMailSend.java:40) 引起:java.net。