【问题标题】:Cannot connect to smtp problems无法连接到 smtp 问题
【发布时间】:2019-03-05 01:18:56
【问题描述】:

我尝试使用 java 创建一些自动发送邮件 但是在构建项目时会出现一些错误。 这是代码。

package sendmail2;

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

public class SendMail2 {

    public static void main(String[] args) {
        try{
            String host ="smtp.gmail.com" ;
            String user = "myemail@gmail.com";
            String pass = "mypassword";
            String to = "my reciever";
            String from = "myemail@gmail.com";
            String subject = "Test App";
            String messageText = "Congrats";
            boolean sessionDebug = false;

            Properties props = System.getProperties();

            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.required", "true");

            java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Session mailSession = Session.getDefaultInstance(props, null);
            mailSession.setDebug(sessionDebug);
            Message msg = new MimeMessage(mailSession);
            msg.setFrom(new InternetAddress(from));
            InternetAddress[] address = {new InternetAddress(to)};
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject(subject); msg.setSentDate(new Date());
            msg.setText(messageText);

           Transport transport=mailSession.getTransport("smtp");
           transport.connect(host, user, pass);
           transport.sendMessage(msg, msg.getAllRecipients());
           transport.close();
           System.out.println("message send successfully");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}

错误是

javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:587; 嵌套异常是: java.net.ConnectException:连接超时:连接 构建成功(总时间:21 秒)

我已经在库中添加了 activation.jar 和 mail.jar。并在 gmail 帐户中开启不太安全的应用访问。

问题是我不知道我的代码是否有问题,以及使它起作用的解决方案

这是我第一次使用堆栈溢出,所以如果我的问题不清楚或难以阅读。请告诉我,给您带来的不便深表歉意。

【问题讨论】:

  • 尝试将端口更改为 465:props.put("mail.smtp.port", "465");
  • 检查您的邮件服务器是否正在侦听端口 587。检查您的代码下载 FakeSmtp.jar 并更改服务器 localhost 和端口 25,如果代码没有给出任何异常意味着它工作正常。
  • //juanlumn 跟随您并将端口更改为 465 但仍然与端口数更改为 465 相同的错误 //vivekdubey 这是消息 javax.mail.MessagingException: STARTTLS is required but host does不支持 STARTTLS {String host ="localhost" ;,props.put("mail.smtp.port", "25");,并且现在也将 fakesmtp 导入库}

标签: java jakarta-mail


【解决方案1】:

JavaMail 常见问题解答有 tips for debugging connection problems

很可能有防火墙阻止您直接连接。 JavaMAil FAQ 还介绍了如何connect through a proxy server

【讨论】:

    猜你喜欢
    • 2017-04-23
    • 2019-09-18
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2014-05-01
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多