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

后端 未结 4 1397
悲&欢浪女
悲&欢浪女 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:22

    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.

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

    1. Open the link: https://myaccount.google.com/security?pli=1#connectedapps
    2. In the Security setting, set ‘Allow less secure apps’ to ON.

    Step 3: Here is a code snippet from the code that I have used and it works without any issues. From 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);
            }
        });
    }
    

    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

提交回复
热议问题