java - java邮件javax.mail.MessagingException:异常
问题描述
下面是我用于测试目的的代码(我使用了与我的项目中使用的相同的库)。
package test;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
public static void send(String from, String password, String to, String sub, String msg) {
// Get properties object
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
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");
// get Session
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
// compose message
try {
MimeMessage message = new MimeMessage(session);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress("sannavdev@gmail.com"));
message.setSubject(sub);
message.setText(msg);
// send message
Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
final String fromEmail = "sannavdev@gmail.com"; // requires valid gmail id
final String password = "sannavdev@1234"; // correct password for gmail id
final String toEmail = "vethsa.teja@broadcom.com"; // can be any email id
EmailSender.send(fromEmail, password, toEmail, "hello javatpoint", "How r u?");
}
}
代码在eclipse中运行良好。但是当我在 IPV 6 环境中运行代码时,出现以下错误:
发送邮件失败 javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:465;嵌套异常是:java.net.SocketTimeoutException:连接超时
解决方案
推荐阅读
- c++ - Qt 应该在构建时跟踪资源的变化吗?
- javascript - 来自对象的数据未在本机反应的任何组件中呈现
- ios - 连接服务协议出错:连接http://127.0.0.1失败
- java - 为多线程设置定时锁
- android - 无法在 android 10 上创建具有已删除文件名的文件
- mstest - .net47 mstest 项目到 .net5
- node.js - Nodejs 单元测试失败时的电子邮件通知
- typescript - Redux-saga,select():“类型‘未知’不可分配给类型‘状态’”
- wordpress - 在 Microsoft Automate 中获取错误的 http 请求
- localhost - 赛普拉斯无法加载 localhost 之外的任何内容。无法使用 CDN 或 Google 字体