gpt4 book ai didi

JavaMail 消息传递异常

转载 作者:行者123 更新时间:2023-12-01 19:19:56 26 4
gpt4 key购买 nike

我编写了一个使用 JavaMail API 发送 gmail 的程序。以下是我的代码:

import java.util.*;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;
import javax.mail.Session;
import javax.mail.Transport;

class emailSend{
public static void main(String[] args) {
String recipient = "receiver@gmail.com";
String sender = "sender@gmail.com";
String host = "smtp.gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.user", sender);
props.put("mail.smtp.password", "password");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);

try
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
message.setSubject("This is the subject");
message.setText("This the message");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com",465,"sender01@gmail.com", "password");
transport.sendMessage(message, message.getAllRecipients());
System.out.println("Mail successfully sent");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

但我收到以下错误:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2197)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at emailSend.main(emailSend.java:29)

我尝试禁用防火墙,但没有用。我应该怎么办?

最佳答案

添加属性:

props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.ssl.checkserveridentity", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.debug", "true");
props.put("mail.smtp.EnableSSL.enable", "true");
props.put("mail.smtp.socketFactory.fallback", "false");

关于JavaMail 消息传递异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59369700/

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