当前位置: 首页 > 知识库问答 >
问题:

MailConnectException:无法连接到主机,端口:smtp。gmail。com,465;超时-1

太叔经赋
2023-03-14

我需要使用Gmail作为SMTP服务器从我的应用程序发送电子邮件。这是我的邮件连接器类,我在一个单独的属性文件中设置了值

    public class EmailConnector {
    

    public static Session sessionCreate() {
        final String fromEmail = ConfigurationManager.getInstance().getProperty(EmailConfig.SENDER_EMAIL.toString());

        final String password = ConfigurationManager.getInstance().getProperty(EmailConfig.SENDER_PASSWORD.toString());

        Properties props = new Properties();
        props.put("mail.smtp.host", ConfigurationManager.getInstance().getProperty(EmailConfig.SMTP_HOST.toString()));

        props.put("mail.smtp.socketFactory.port",
                ConfigurationManager.getInstance().getProperty(EmailConfig.SSL_PORT.toString()));

        props.put("mail.smtp.socketFactory.class",
                ConfigurationManager.getInstance().getProperty(EmailConfig.SSL_FACTORY_CLASS.toString()));

        props.put("mail.smtp.auth",
                ConfigurationManager.getInstance().getProperty(EmailConfig.SMTP_AUTHENTICATION.toString()));

        props.put("mail.smtp.port", ConfigurationManager.getInstance().getProperty(EmailConfig.SMTP_PORT.toString()));

        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, password);
            }
        };
        return Session.getDefaultInstance(props, auth);
    }
}

属性:

#Email send configuration
SENDER_EMAIL = abcalerts@gmail.com
SENDER_PASSWORD = abcalert321
SMTP_HOST = smtp.gmail.com
SSL_PORT = 465
SMTP_AUTHENTICATION = true
SMTP_PORT = 465
SSL_FACTORY_CLASS = javax.net.ssl.SSLSocketFactory

然后我实现了一个邮件发送者类,名为“GroupEmail.class”

public class GroupEmail {

    public void sendEmail() throws IOException {
        String recipient = "nirmalauwucst@gmail.com";

        Session session = EmailConnector.sessionCreate();
        /* subject of email */
        String emailSubject = "ABC_Alert";
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
            msg.addHeader("format", "flowed");
            msg.addHeader("Content-Transfer-Encoding", "8bit");

            msg.setFrom(new InternetAddress("abcalerts@gmail.com", "ABC Alerts"));

            msg.setReplyTo(InternetAddress.parse("abcalerts@gmail.com"));

            msg.setSubject(emailSubject, "UTF-8");

            msg.setSentDate(new Date());
            /* buyer email address */
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));

            /* Create the message body part */
            msg.setText("A new Test-Alert from AB_Alerts");

            /* Send message */
            Transport.send(msg, "abcalerts@gmail.com", "abcalert321");

        } catch (MessagingException | UnsupportedEncodingException e) {
            SystemLogger.logErrorMessege(this, e);
        }
    }

}

毕竟,我在需要触发要发送的电子邮件的地方调用了“GroupEmail.class”。

GroupEmail groupEmail = new GroupEmail();
        groupEmail.sendEmail(); 

我在localhost使用Tomcat v8服务器,当应用程序工作时,我得到了以下异常。

98656 [http-nio-8080-exec-9] ERROR it.nmad.test.abcalert.notification.template.email.GroupEmail  - Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
  nested exception is:
    java.net.SocketException: Permission denied: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2100)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:699)
    at javax.mail.Service.connect(Service.java:388)
    at javax.mail.Service.connect(Service.java:246)
    at javax.mail.Service.connect(Service.java:195)
    at javax.mail.Transport.send0(Transport.java:254)
    at javax.mail.Transport.send(Transport.java:124)
..more

共有2个答案

严琨
2023-03-14

修复这些常见的JavaMail错误。

按照JavaMail常见问题解答中的连接调试提示进行操作。

很可能是防火墙或防病毒产品阻止了你的连接。

如果Tomcat使用Java安全管理器运行,JavaMail FAQ会提供有关配置安全权限的信息。如果这没有帮助,JavaMail FAQ还会提供有关调试安全权限问题的信息。

我有没有提到你应该阅读JavaMail常见问题解答?:-)

谷梁煌
2023-03-14

我知道这是一个很晚的答案,但想分享我的经验,当我面对同样的问题,并尝试了几乎Java核心邮件api,Apache邮件api和Spring也为MimeMessage

我用Javajdk1.7.0_80尝试了50次,但多次失败,出现上述异常,然后我转到jdk1.8.0_151。

现在,在说明源代码之前,我想分享一下我的配置。

转到Gmail

允许不太安全的应用程序:关闭(意味着我的应用程序不太安全)

2步验证:关闭

应用程序密码(点击它,Google将为您生成一个16个字符长的密码,稍后完成,使用这个16个字符长的密码更改您的gmail密码(没有任何空格))。

现在,我的源代码是:

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

        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.gmail.com");
        mailSender.setPort(465);

        mailSender.setUsername(String.valueOf(resourceList.get(0)));
        mailSender.setPassword(String.valueOf(resourceList.get(1)));

        //from email id and password
        System.out.println("Username is : " + String.valueOf(resourceList.get(0)).split("@")[0]);
        System.out.println("Password is : " + String.valueOf(resourceList.get(1)));

        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");

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo(toMailId);
            helper.setSubject("Welcome to Subject Part");
            helper.setText(htmlMessage, true);

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

    }

}

Spring mail的调试日志如下所示:

Username is : exampleusername
Password is : abcdefghijklmnop
DEBUG: JavaMail version 1.6.0
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
220 smtp.gmail.com ESMTP 12sm62330270pfr.147 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 465

EHLO Administrator
250-smtp.gmail.com at your service, [157.48.195.205]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: STARTTLS requested but already using SSL
DEBUG SMTP: protocolConnect login, host=smtp.gmail.com, user=exampleusername@gmail.com, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2 
DEBUG SMTP: Using mechanism LOGIN
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<Administrator@Administrator>
250 2.1.0 OK 12sm62330270pfr.147 - gsmtp
RCPT TO:<somebody@live.com>
250 2.1.5 OK 12sm62330270pfr.147 - gsmtp
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   somebody@live.com
DATA
354  Go ahead 12sm62330270pfr.147 - gsmtp
Date: Mon, 19 Feb 2018 18:55:29 +0530 (IST)
To: somebody@live.com
Message-ID: <2023168072.2.1519046734494@Administrator>
Subject: Welcome to Subject Part
MIME-Version: 1.0
Content-Type: multipart/mixed; 
    boundary="----=_Part_0_1884507527.1519046720984"

------=_Part_0_1884507527.1519046720984
Content-Type: multipart/related; 
    boundary="----=_Part_1_1634862487.1519046721031"

------=_Part_1_1634862487.1519046721031
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

<!DOCTYPE html>
<html>
Your html page source code is here
</html>

------=_Part_1_1634862487.1519046721031--

------=_Part_0_1884507527.1519046720984--
.
250 2.0.0 OK 1519046738 12sm62330270pfr.147 - gsmtp
DEBUG SMTP: message successfully delivered to mail server
QUIT
221 2.0.0 closing connection 12sm62330270pfr.147 - gsmtp

此外,请检查您的互联网连接、防病毒设置和防火墙访问是否不间断,希望这能帮助许多人避免浪费时间。

 类似资料: