Properties for sending email through gmail

I am currently ready to write a simple program to send email through gmail to a gmail account. I tried various methods, but often I end up with the same error: "Could not connect to the SMTP host: smtp.gmail.com, port: 587;"

Does it have anything to do with property settings. Here is a snippet from my program. Finding a solution :)

Thank you in advance

public static boolean SendMail(String from, String password, String message, String to[]){
        String host = "smtp.gmail.com";
        Properties prop = System.getProperties();
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", host);
        prop.put("mail.smtp.user", from);
        prop.put("mail.smtp.password", password);
        prop.put("mail.smtp.port", 587); //prop.put("mail.smtp.port", 465);//
        prop.put("mail.smtp.auth", "true");

         // check for the first value in the name of props or prop
        Session session = Session.getDefaultInstance(prop, null);
        MimeMessage mimemsg = new MimeMessage(session);

        try{
            mimemsg.setFrom(new InternetAddress(from));

            // Get reciepents Address
            InternetAddress[] toAddress = new InternetAddress[to.length];
            for (int i=0;i<to.length;i++){
                toAddress[i] = new InternetAddress(to[i]);
            }

            //Add all toAddress to mimemessage
            for(int j=0;j<toAddress.length;j++){
                mimemsg.addRecipient(RecipientType.TO, toAddress[j]);

            }

            // Add Subject.
            mimemsg.setSubject(" MAIL from JAVA Program");
            // Add Message to the content(input to the method )
            mimemsg.setText(message);

            Transport trans = session.getTransport("smtp");
            trans.connect(host,from,password);
            trans.sendMessage(mimemsg, mimemsg.getAllRecipients());
            trans.close();
            return true;

        }catch(MessagingException me){
            me.printStackTrace();
        }


    return false;
}
+4
source share
3 answers

Your settings look correct. SMail port GMail 587 for TLS. This seems like a network connection problem (host name is not resolved).

  • Double check your credentials.
  • telnet smtp.gmail.com 587 . SMTP?
  • IP-. : IP-, . .
0

, from password props.put("mail.smtp.port", "465"); 465

Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from,password);
                }
            });

:

props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
0

The presence of props.put ("mail.smtp.host", "173.194.78.108"); instead of props.put ("mail.smtp.host", "smtp.gmail.com"); solved a problem

0
source

Source: https://habr.com/ru/post/1525274/


All Articles