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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38608089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:27:51  来源:igfitidea点击:

Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection timed out: connect

javaeclipseemail

提问by zainab rizvi

Here is the code of the application. I have been trying to run this using eclipse IDE. I also added all the required java mail jar files namely dsn.jar,imap.jar,mailapi.jar,pop3.jar,smtp.jar,mail.jar. But it gives the following error Could not connect to SMTP host: smtp.gmail.com, port: 587.

这是应用程序的代码。我一直在尝试使用 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

There's no firewall blocking access because a reply is received on pinging smtp.gmail.com. I have even tried it this way :

没有防火墙阻止访问,因为在 ping smtp.gmail.com 时收到回复。我什至这样尝试过:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection timed out: connect at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642) 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 PlainTextEmailSender.sendPlainTextEmail(PlainTextEmailSender.java:50) at PlainTextEmailSender.main(PlainTextEmailSender.java:73) Caused by: java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:319) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)

javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:587;嵌套异常是:java.net.ConnectException:连接超时:在 com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972) 连接 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) at javax.mail.Transport.send(Transport.java:124) at PlainTextEmailSender.sendPlainTextEmail(PlainTextEmailSender.java:50) at PlainTextEmailSender.main(PlainTextEmailSender.java:73)引起:java.net.ConnectException:连接超时:

    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();
            }
        }
    }

采纳答案by walen

As I said, there's nothing wrong with your code. If anything, just to do some testing, try to drop the Authentication part to see if that works:

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

    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

    }

That's the code I'm using every day to send dozens of emails from my application, and it is 100% guaranteed to work -- as long as smtp.gmail.com:587is reachable, of course.

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

回答by ArifMustafa

Email succeeded through Gmailusing JDK 7with below Gmailsettings.

通过Gmail使用JDK 7以下设置成功发送电子邮件。Gmail

Go to GmailSettings>Accounts and Import>Other Google Account settings>and under Sign-in & security

转到> > >及下方GmailSettingsAccounts and ImportOther Google Account settingsSign-in & security

  1. 2-Step Verification: Off
  2. Allow less secure apps: ON
  3. App Passwords: 1 password(16 characters long), later replaced the current password with this.
  1. 2-Step Verification: Off
  2. Allow less secure apps: ON
  3. App Passwords: 1 password(16 个字符长),后来用这个替换了当前密码。

used following maven dependencies:

使用了以下 Maven 依赖项:

spring-core:4.2.2
spring-beans:4.2.2
spring-context:4.2.2
spring-context-support:4.2.2
spring-expression:4.2.2
commons-logging:1.2

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

and my source code is:

我的源代码是:

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;
import java.util.List;
import java.util.Properties;

public class Email {

    public final void prepareAndSendEmail(String htmlMessage, String toMailId) {

        final OneMethod oneMethod = new OneMethod();
        final List<char[]> resourceList = oneMethod.getValidatorResource();

        //Spring Framework JavaMailSenderImplementation    
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.gmail.com");
        mailSender.setPort(465);

        //setting username and password
        mailSender.setUsername(String.valueOf(resourceList.get(0)));
        mailSender.setPassword(String.valueOf(resourceList.get(1)));

        //setting Spring JavaMailSenderImpl Properties
        Properties mailProp = mailSender.getJavaMailProperties();
        mailProp.put("mail.transport.protocol", "smtp");
        mailProp.put("mail.smtp.auth", "true");
        mailProp.put("mail.smtp.starttls.enable", "true");
        mailProp.put("mail.smtp.starttls.required", "true");
        mailProp.put("mail.debug", "true");
        mailProp.put("mail.smtp.ssl.enable", "true");
        mailProp.put("mail.smtp.user", String.valueOf(resourceList.get(0)));

        //preparing Multimedia Message and sending
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo(toMailId);
            helper.setSubject("I achieved the Email with Java 7 and Spring");
            helper.setText(htmlMessage, true);//setting the html page and passing argument true for 'text/html'

            //Checking the internet connection and therefore sending the email
            if(OneMethod.isNetConnAvailable())
                mailSender.send(mimeMessage);
            else
                JOptionPane.showMessageDialog(null, "No Internet Connection Found...");
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

}

Hope this will help someone.

希望这会帮助某人。

回答by criscan

Try this steps

试试这个步骤

Step 2: Send mail from your device or application

第 2 步:从您的设备或应用程序发送邮件

If you connect using SSL or TLS, you can send mail to anyone with smtp.gmail.com.

如果您使用 SSL 或 TLS 进行连接,则可以使用 smtp.gmail.com 向任何人发送邮件。

Note: Before you start the configuration, we recommend you set up App passwords for the the desired account. Learn more at Sign in using App Passwords and Manage a user's security settings.

注意:在开始配置之前,我们建议您为所需的帐户设置应用程序密码。在使用应用密码登录和管理用户的安全设置中了解更多信息。

Connect to smtp.gmail.com on port 465, if you're using SSL. (Connect on port 587 if you're using TLS.) Sign in with a Google username and password for authentication to connect with SSL or TLS. Ensure that the username you use has cleared the CAPTCHA word verification test that appears when you first sign in.

如果您使用 SSL,请通过端口 465 连接到 smtp.gmail.com。(如果您使用的是 TLS,则在端口 587 上连接。)使用 Google 用户名和密码登录以进行身份​​验证以连接 SSL 或 TLS。确保您使用的用户名已通过首次登录时出现的 CAPTCHA 字词验证测试。

回答by Aj Tech Developer

For all those who are still looking for the answer explained in a simple way, here is the answer:

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

Step 1: Most of the Anti Virus programs block sending of Email from the computer through an internal application. Hence if you get an error, then you will have to disable your Anti Virus program while calling these Email sending methods/APIs.

步骤 1:大多数防病毒程序会阻止通过内部应用程序从计算机发送电子邮件。因此,如果您收到错误消息,那么您将不得不在调用这些电子邮件发送方法/API 时禁用您的防病毒程序。

Step 2: SMTP access to Gmail is disabled by default. To permit the application to send emails using your Gmail account follow these steps

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

  1. Open the link: https://myaccount.google.com/security?pli=1#connectedapps
  2. In the Security setting, set ‘Allow less secure apps' to ON.
  1. 打开链接:https: //myaccount.google.com/security?pli=1#connectedapps
  2. 在安全设置中,将“允许安全性较低的应用程序”设置为ON

Step 3: Here is a code snippet from the code that I have used and it works without any issues. From EmailService.java:

第 3 步:这是我使用过的代码中的一个代码片段,它可以正常工作。从 EmailService.java:

private Session getSession() {
    //Gmail Host
    String host = "smtp.gmail.com";
    String username = "[email protected]";
    //Enter your Gmail password
    String password = "";

    Properties prop = new Properties();
    prop.put("mail.smtp.auth", true);
    prop.put("mail.smtp.starttls.enable", "true");
    prop.put("mail.smtp.host", host);
    prop.put("mail.smtp.port", 587);
    prop.put("mail.smtp.ssl.trust", host);

    return Session.getInstance(prop, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
}

I have also written a blog post and a working application on GitHub with these steps. Please check: http://softwaredevelopercentral.blogspot.com/2019/05/send-email-in-java.html

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