无法连接到SMTP主机:smtp.gmail.com,port:587; 嵌套异常是:java.net.ConnectException:连接超时:连接

zai*_*zvi 8 java eclipse email

这是应用程序的代码.我一直在尝试使用eclipse IDE运行它.我还添加了所有必需的java邮件jar文件 dsn.jar,imap.jar,mailapi.jar,pop3.jar,smtp.jar,mail.jar.但它给出了以下错误Could not connect to SMTP host: smtp.gmail.com, port: 587.

没有防火墙阻止访问,因为在pinging smtp.gmail.com上收到了回复.我甚至用这种方式尝试过:

javax.mail.MessagingException:无法连接到SMTP主机:smtp.gmail.com,port:587; 嵌套异常是:java.net.ConnectException:连接超时:com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java :642)在javax.mail.Service.connect(Service.java:317)的javax.mail.Service.connect(Service.java:176)javax.mail.Service.connect(Service.java:125)javax .mail.Transport.send0(Transport.java:194)位于PlainTextEmailSender.main的PlainTextEmailSender.sendPlainTextEmail(PlainTextEmailSender.java:50)的javax.mail.Transport.send(Transport.java:124)(PlainTextEmailSender.java:73)引发者:java.net.ConnectException:连接超时:在java.net.AbstractStackPocketImpl.smplConnect(未知来源)java.net.AbstractStackPocketImpl.doConnect(未知来源)的java.net.DualStackPlainSocketImpl.connect0(本地方法)连接java.net.Pl上java.net.AbstractPlainSocketImpl.connect(未知来源)的java.net.AbstractPlainSocketImpl.connectToAddress(未知来源)来自java.net.Socks.connect(未知来源)的java.net.SocksSocketImpl.connect(未知来源)的ainSocketImpl.connect(未知来源),位于com.sun.mail的java.net.Socket.connect(未知来源). com.sun.mail.tt.MtTP.Transport.openServer上的com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)中的util.SocketFetcher.createSocket(SocketFetcher.java:319)(SMTPTransport.java:1938)

    package net.codejava.mail;

    import java.util.Date;
    import java.util.Properties;

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

    public class PlainTextEmailSender {

        public void sendPlainTextEmail(String host, String port,
                final String userName, final String password, String toAddress,
                String subject, String message) throws AddressException,
                MessagingException {

            // sets SMTP server properties
            Properties properties = new Properties();
            properties.put("mail.smtp.host", host);
            properties.put("mail.smtp.port", port);
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.starttls.enable", "true");

            // creates a new session with an authenticator
            Authenticator auth = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(userName, password);
                }
            };

            Session session = Session.getInstance(properties, auth);

            // creates a new e-mail message
            Message msg = new MimeMessage(session);

            msg.setFrom(new InternetAddress(userName));
            InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
            msg.setRecipients(Message.RecipientType.TO, toAddresses);
            msg.setSubject(subject);
            msg.setSentDate(new Date());
            // set plain text message
            msg.setText(message);

            // sends the e-mail
            Transport.send(msg);

        }

        /**
         * Test the send e-mail method
         *
         */
        public static void main(String[] args) {
            // SMTP server information
            String host = "smtp.gmail.com";
            String port = "587";
            String mailFrom = "user_name";
            String password = "password";

            // outgoing message information
            String mailTo = "email_address";
            String subject = "Hello my friend";
            String message = "Hi guy, Hope you are doing well. Duke.";

            PlainTextEmailSender mailer = new PlainTextEmailSender();

            try {
                mailer.sendPlainTextEmail(host, port, mailFrom, password, mailTo,
                        subject, message);
                System.out.println("Email sent.");
            } catch (Exception ex) {
                System.out.println("Failed to sent email.");
                ex.printStackTrace();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 5

对于所有仍在寻找以简单方式解释的答案的人,答案如下:

\n\n

步骤 1: \n大多数防病毒程序都会阻止通过内部应用程序从计算机发送电子邮件。因此,如果您收到错误,则在调用这些电子邮件发送方法/API 时必须禁用防病毒程序。

\n\n

步骤 2:\n默认情况下禁用对 Gmail 的 SMTP 访问。要允许应用程序使用您的 Gmail 帐户发送电子邮件,请按照以下步骤操作

\n\n
    \n
  1. 打开链接: https: //myaccount.google.com/security? pli=1#connectedapps
  2. \n
  3. 在安全设置中,将 \xe2\x80\x98Allow less secure apps\xe2\x80\x99 设置为ON
  4. \n
\n\n

步骤 3:\n这是我使用过的代码中的一个代码片段,它可以正常工作,没有任何问题。来自 EmailService.java:

\n\n
private Session getSession() {\n    //Gmail Host\n    String host = "smtp.gmail.com";\n    String username = "techdeveloper.aj@gmail.com";\n    //Enter your Gmail password\n    String password = "";\n\n    Properties prop = new Properties();\n    prop.put("mail.smtp.auth", true);\n    prop.put("mail.smtp.starttls.enable", "true");\n    prop.put("mail.smtp.host", host);\n    prop.put("mail.smtp.port", 587);\n    prop.put("mail.smtp.ssl.trust", host);\n\n    return Session.getInstance(prop, new Authenticator() {\n        @Override\n        protected PasswordAuthentication getPasswordAuthentication() {\n            return new PasswordAuthentication(username, password);\n        }\n    });\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我还按照这些步骤在 GitHub 上编写了一篇博客文章和一个工作应用程序。请检查:http ://softwaredevelopercentral.blogspot.com/2019/05/send-email-in-java.html

\n


wal*_*len 3

正如我所说,您的代码没有任何问题。如果有的话,只是做一些测试,尝试删除身份验证部分以查看是否有效:

    public void sendPlainTextEmail(String host, String port,
            final String userName, final String password, String toAddress,
            String subject, String message) throws AddressException,
            MessagingException {

        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
// *** BEGIN CHANGE
        properties.put("mail.smtp.user", userName);

        // creates a new session, no Authenticator (will connect() later)
        Session session = Session.getDefaultInstance(properties);
// *** END CHANGE

        // creates a new e-mail message
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        // set plain text message
        msg.setText(message);

// *** BEGIN CHANGE
        // sends the e-mail
        Transport t = session.getTransport("smtp");
        t.connect(userName, password);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
// *** END CHANGE

    }
Run Code Online (Sandbox Code Playgroud)

这是我每天使用的代码,从我的应用程序发送数十封电子邮件,并且 100% 保证它可以工作——当然smtp.gmail.com:587,只要可以访问。