繁体   English   中英

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

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

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

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

转到Gmail 设置 > 帐户和导入 > 其他Google帐户设置 >,然后在登录和安全性下

  1. 两步验证:关闭
  2. 允许安全性较低的应用:开启
  3. 应用密码:1个密码 (16个字符长),稍后用此替换当前密码。

使用以下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>

我的源代码是:

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

    }

}

希望这会对某人有所帮助。

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

    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

    }

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

尝试这个步骤

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

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

注意:在开始配置之前,我们建议您为所需帐户设置应用程序密码。 有关使用应用密码登录和管理用户安全设置的详细信息,请参阅。

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

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

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

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

  1. 打开链接: https//myaccount.google.com/security?pli = 1#connectedctedapps
  2. 在“安全”设置中,将“允许较少安全的应用”设置为“ 开”

第3步:这是我使用的代码的代码片段,它没有任何问题。 来自EmailService.java:

private Session getSession() {
    //Gmail Host
    String host = "smtp.gmail.com";
    String username = "techdeveloper.aj@gmail.com";
    //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);
        }
    });
}

我还在GitHub上写了一篇博客文章和一个有用的应用程序。 请检查: http//softwaredevelopercentral.blogspot.com/2019/05/send-email-in-java.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM