gpt4 book ai didi

java - 通过 GMail 使用 SMTP 时如何修复 javax.mail.MessagingException?

转载 作者:行者123 更新时间:2023-12-01 04:37:58 25 4
gpt4 key购买 nike

我无法执行可公开通过 Gmail 发送电子邮件的代码。我认为这可能是网络问题,因为我正在工作,尽管我可以通过 cmd 提示符 ping Gmail:ping smtp.gmail.com

这是我正在使用的代码(来自 this page ):

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;


class tester {
public static void main(String args[]) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.stmp.user", "username of the sender");
//If you want you use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.password", "password of the sender");
// If you want to use SSL
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");
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "username";
String password = "password";
return new PasswordAuthentication("username","password");
}
});
String to = "me@gmail.com";
String from = "from@gmail.com";
String subject = "Testing...";
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText("JAVA is the BEST");
Transport transport = session.getTransport("smtp");
transport.send(msg);
System.out.println("E-mail sent !");
} catch(Exception exc) {
System.out.println(exc);
}
}
}

我已将用户名和密码字段更改为正确的。有哪些因素可能会导致这种情况?我为此使用了自己的代码和许多其他公开可用的代码,但遇到了相同的错误。我也尝试通过端口 587 运行并收到相同的错误。

这是错误:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is: java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at GoogleMail.sendMail(GoogleMail.java:45)

最佳答案

我在 cmd 提示符下使用了 telnet smtp.gmail.com 465telnet smtp.gmail.com 587 命令,两者都可以无法连接。我认为它与我所连接的网络相关联。我无法提供除此之外的任何信息,如果我发现更多信息,我将进行更新。

关于java - 通过 GMail 使用 SMTP 时如何修复 javax.mail.MessagingException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17048341/

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