gpt4 book ai didi

java - 为什么在 Javamail 中连接超时?

转载 作者:行者123 更新时间:2023-12-04 18:02:06 25 4
gpt4 key购买 nike

我正在尝试在 eclipse 中使用 javamail 通过 gmail 发送电子邮件。每次我收到 javax.mail.MessagingException

异常(exception)

 DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
javax.mail.MessagingException: Could not connect to SMTP host:

smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect

代码
package org.itc.utility;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.itc.model.User;

public class SendEmail {
public User sendingEmail(User user)
{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", 587);
props.put("mail.smtp.socketFactory.port", 587);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtp");
Session mailSession = null;

mailSession = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("<yogeshvbhat@gmail.com>", "<zc516z918>");
}
});


try {


Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);

message.setSubject("Sample Subject");
message.setFrom(new InternetAddress("yogeshvbhat@gmail.com"));
String []to = new String[]{"yogeshyvb@gmail.com"};
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[0]));
String body = "Sample text";
message.setContent(body,"text/html");
transport.connect();

transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (Exception exception) {
System.out.println(exception);
}
return user;
}
}

每次它跳过 try block 时,我都会收到异常。有什么帮助吗?

最佳答案

仅添加以下属性:

    Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
另外,请检查您的 Gmail 设置:
Set up 2-Step Verification

关于java - 为什么在 Javamail 中连接超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33609263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com