0
votes

It is showing following error ::

Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587, response: 421 at SendMail.main(SendMail.java:54) Caused by: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587, response: 421 at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2088) 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) at SendMail.main(SendMail.java:49) Java Result: 1 BUILD SUCCESSFUL (total time: 2 seconds)

and my code is:

`public class SendMail {

    public static void main(String[] args) throws Exception{

        final String smtp_host = "smtp.gmail.com";
        final String smtp_username = "[email protected]";
        final String smtp_password = "xxxxxx";
        final String smtp_connection = "TLS"; 

        final String toEmail="[email protected]";
        final String fromEmail="[email protected]";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");

       if (smtp_connection.equals("TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.port", "587");
        } else{
                props.put("mail.smtp.socketFactory.port", "465");
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.port", "465");
        }

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(smtp_username, smtp_password);
                }
          });

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(fromEmail, "NoReply"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(toEmail, "Mr. Recipient"));
            msg.setSubject("Welcome To JavaMail API");
            msg.setText("JavaMail API Test - Sending email example through remote smtp server");
            Transport.send(msg);
            System.out.println("Email sent successfully...");
        } catch (AddressException e) {
            throw new RuntimeException(e);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}`
2
Check what an SMTP 421 response means. Usually if refers to the server declining your connection temporarily (often because you have tried too many connections)Brody
To connect to google smtp server, make sure you are using TLS/SSL. It is requiredmubeen

2 Answers

1
votes

Below is the working code. You are not setting an SSL socket factory in the non-TLS case.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Email {

private static String USER_NAME = "username";  // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "password"; // GMail password

private static String RECIPIENT = "[email protected]";

public static void main(String[] args) {
    String from = USER_NAME;
    String pass = PASSWORD;
    String[] to = { RECIPIENT }; // list of recipient email addresses
    String subject = "Java send mail example";
    String body = "hi ....,!";

    sendFromGMail(from, pass, to, subject, body);
}

private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
    Properties props = System.getProperties();
  String host = "smtp.gmail.com";

    props.put("mail.smtp.starttls.enable", "true");

    props.put("mail.smtp.ssl.trust", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");


    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {


        message.setFrom(new InternetAddress(from));
        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }



        message.setSubject(subject);
        message.setText(body);


        Transport transport = session.getTransport("smtp");


        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

    }
    catch (AddressException ae) {
        ae.printStackTrace();
    }
    catch (MessagingException me) {
        me.printStackTrace();
    }
    }
   } 
0
votes

To connect to google SMTP server, make sure you are using TLS/SSL. It is required. Go to gmail account Click on the Forwarding/IMAP tab and scroll down to the IMAP Access section: IMAP must be enabled in order for emails to be properly copied to your sent folder.

And Try Change This

if (smtp_connection.equals("TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.port", "587");
        } else{
                props.put("mail.smtp.socketFactory.port", "465");
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.port", "465");
        }

To This

properties.put("mail.smtp.starttls.enable", "true"); 
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.user", "username"); // User name
properties.put("mail.smtp.password", "password"); // password
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");