你好stackoverflow的人!
我一直在尝试使用JavaMail API
// Recipient's email ID needs to be mentioned.
String to = "toaddrs@gmail.com";//change accordingly
// Sender's email ID needs to be mentioned
String from = "fromaddrs@gmail.com";//change accordingly
final String email = "emailaddrs@gmail.com";//change accordingly
final String password = "xxxxxxxxx";//change accordingly
// Assuming you are sending email through relay.jangosmtp.net
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "465");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Now set the actual message
message.setText("Hello, this is sample for to check send "
+ "email using JavaMailAPI ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
程序执行后我似乎没有错误:
java.lang.RuntimeException:javax.mail.MessagingException:无法连接到SMTP主机:smtp.gmail.com,port:465; 嵌套异常是: java.net.ConnectException:连接超时:connect
任何人都可以帮我解决这个问题吗??? << - >是的,我已将GMail配置为安全性较低的应用程序选项....>>
事先提前!!
答案 0 :(得分:0)
使用TLS通过Gmail SMTP服务器发送邮件时,应使用端口587
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
端口 465 用于使用SSL发送电子邮件,应该看起来像这样
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
答案 1 :(得分:0)
您的防火墙或代理或防病毒程序可能会阻止直接连接。
JavaMail常见问题解答包含tips for connecting through a proxy和debugging tips to help determine why you can't connect。