gpt4 book ai didi

java - 发送邮件时出错 - ConnectException

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:51:33 27 4
gpt4 key购买 nike

我使用下面的 Java 代码来发送电子邮件。

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

public class SendEmail
{
public static void main(String [] args)
{

String to = "abcd@gmail.com";
String from = "web@gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("smtp.gmail.com", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to))
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

当我运行该文件时,出现以下错误:

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)

Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)

如果有人可以帮助我,我将不胜感激。

如何解决ConnectException

最佳答案

我可以看到您正在尝试使用 Gmail 作为您的 SMTP 服务器。此行不正确:

properties.setProperty("smtp.gmail.com", host);

您使用主机名作为属性名,这是不正确的。因为您没有设置 mail.smtp.host 属性,所以 JavaMail 会尝试连接到“localhost”。改为设置以下属性:

properties.put("mail.smtp.starttls.enable", "true"); 
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.user", "username"); // User name
properties.put("mail.smtp.password", "password"); // password
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");

关于java - 发送邮件时出错 - ConnectException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14089533/

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