Java – Unable to send e-mail through Java

emailgmailgmail-popjavasmtp

After going through post provided for the same problem, I have written the following code. But I am getting the following exception :

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

public static void main(String[] args) {

    String to = "xxx@gmail.com" // valid gmail address.     
    String from = "yyy@gmail.com"; // valid gmail address

    String host = "smtp.gmail.com";
    String password = "****"; // password of the gmaill acc used in from

    int port = 587;


    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.setProperty("mail.smtp.host",host );
    properties.setProperty("mail.smtp.user", from);
    properties.setProperty("mail.smtp.password", password);
    properties.setProperty("mail.smtp.port", "587");
    properties.setProperty("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(properties,null);

    try {

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        message.setSubject("Test Mail");

        message.setText("This is just a test mail generated");

       Transport transport = session.getTransport("smtp");
       transport.connect(host,from,password);
       InternetAddress[] addresses = new InternetAddress[1];
       addresses[0] = new InternetAddress(to);
       transport.sendMessage(message,addresses);


        System.out.println("Message Sent Successfully");
    }catch(MessagingException excp){
        System.out.println(excp);
    }

}

Can somebody tell mistake that I am doing. Is there any setting in my gmail account which needs to be set to use the gmail smtp server?

Best Answer

Try the following code. You will need to download javax.mail package (A jar file), I assumed that you would have already that jar file because you have tried this code and consequently, I don't provide the link to download that jar file. Set the class path properly and import the necessary packages. Take care with the firewall and the host port you selected.

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

final class MailClient
{
    private class SMTPAuthenticator extends Authenticator
    {
        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password)
        {
             authentication = new PasswordAuthentication(login, password);
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication()
        {
             return authentication;
        }
    }

    public void mail()
    {
        try
        {
            String from = "xyz.com";
            String to = "abc.com";
            String subject = "Your Subject.";
            String message = "Message Text.";
            String login = "xyz.com";
            String password = "password";

            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);

           try
           {
                msg.setText(message);
                msg.setSubject(subject);
                msg.setFrom(new InternetAddress(from));
                msg.addRecipient(Message.RecipientType.TO,
                new InternetAddress(to));
                Transport.send(msg);
           }
           catch (MessagingException ex)
           {
                Logger.getLogger(MailClient.class.getName()).
                log(Level.SEVERE, null, ex);
           }
        }
    }
}

final public class Main
{
    public static void main(String...args)
    {
        new MailClient().mail();
    }
}