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

后端 未结 4 1401
悲&欢浪女
悲&欢浪女 2021-02-14 22:56

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.j

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-14 23:16

    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:587 is reachable, of course.

提交回复
热议问题