在浏览了针对相同问题提供的帖子后,我编写了以下代码。但我得到以下异常:
javax.mail.MessagingException:
无法连接到 SMTP 主机:smtp.gmail.com,端口:587;嵌套异常是:java.net.ConnectException:连接超时:连接
public static void main(String[] args) {
String to = "xxx@gmail.com" // valid gmail address.
String from = "yyy@gmail.com"; // valid gmail address
String host = "smtp.gmail.com";
String password = "****"; // password of the gmaill acc used in from
int port = 587;
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host",host );
properties.setProperty("mail.smtp.user", from);
properties.setProperty("mail.smtp.password", password);
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,null);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Mail");
message.setText("This is just a test mail generated");
Transport transport = session.getTransport("smtp");
transport.connect(host,from,password);
InternetAddress[] addresses = new InternetAddress[1];
addresses[0] = new InternetAddress(to);
transport.sendMessage(message,addresses);
System.out.println("Message Sent Successfully");
}catch(MessagingException excp){
System.out.println(excp);
}
}
有人能说出我正在做的错误吗?我的 gmail 帐户中是否有任何设置需要设置为使用 gmail smtp 服务器?