Archit Arora
Archit Arora

Reputation: 2626

Cannot connect to Gmail SMTP using JavaMail api

I have written the following two java classes -

public class EmailUtil {

    public static void sendEmail(Session session, String toEmail, String subject, String body){
        try
        {
          MimeMessage msg = new MimeMessage(session);
          //set message headers
          msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
          msg.addHeader("format", "flowed");
          msg.addHeader("Content-Transfer-Encoding", "8bit");

          msg.setFrom(new InternetAddress("no_reply@no_reply.com", "NoReply-NP"));

          msg.setReplyTo(InternetAddress.parse("no_reply@no_reply.com", false));

          msg.setSubject(subject, "UTF-8");

          msg.setText(body, "UTF-8");

          msg.setSentDate(new Date());

          msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
          System.out.println("Message is ready");
          Transport.send(msg); 

          System.out.println("EMail Sent Successfully!!");
        }
        catch (Exception e) {
          e.printStackTrace();
        }
    }
}


public class TLSEmail {


    public static void main(String[] args) {
        final String fromEmail = "*****@gmail.com"; 
        final String password = "*****"; 
        final String toEmail = "****@gmail.com"; 

        System.out.println("TLSEmail Start");
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
        props.put("mail.smtp.port", "587"); //TLS Port
        props.put("mail.smtp.auth", "true"); //enable authentication
        props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS

                //create Authenticator object to pass in Session.getInstance argument
        Authenticator auth = new Authenticator() {
            //override the getPasswordAuthentication method
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, password);
            }
        };
        Session session = Session.getInstance(props, auth);

        EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body");

    }


}

When I run this, I get the following error -

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.SocketException: Permission denied: connect

How Do I fix this? Please help! PS - I am not using two-step verification Thanks in advance!

Upvotes: 0

Views: 6965

Answers (3)

Dev006
Dev006

Reputation: 87

Follow this steps:

  1. Disable "Two factor authentication" in Your Email
  2. Navigate to: "https://myaccount.google.com/lesssecureapps?pli=1" and turn on "Access for less secure apps"
  3. Download JavaMail API "https://www.oracle.com/technetwork/java/javamail/index-138643.html" and Add it to your library

CODE

import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class email_try {
 public static void main(String ap[]) {
  String myEmail = "YOUR EMAIL";
  String password = "YOUR PASSWORD";
  String opponentEmail = "THEIR EMAIL";
  Properties pro = new Properties();
  pro.put("mail.smtp.host", "smtp.gmail.com");
  pro.put("mail.smtp.starttls.enable", "true");
  pro.put("mail.smtp.auth", "true");
  pro.put("mail.smtp.port", "587");
  Session ss = Session.getInstance(pro, new javax.mail.Authenticator() {
   @Override
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(myEmail, password);
   }
  });
  try {
   Message msg = new MimeMessage(ss);
   msg.setFrom(new InternetAddress(myEmail));
   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(opponentEmail));
   msg.setSubject("Your Wish");
   msg.setText("java email app");
   Transport trans = ss.getTransport("smtp");
   Transport.send(msg);
   System.out.println("message sent");
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }
 }
}

TRY THIS CODE AND PUT CORRECT EMAIL ID AND PASSWORD

Upvotes: 1

Kevin STS
Kevin STS

Reputation: 173

To make it work I had :

  1. Enabled POP/IMAP for my gmail account.
  2. Allowing less secure apps to access your account via this url: https://www.google.com/settings/security/lesssecureapps.

I hope this help somebody else.

Upvotes: 3

Archit Arora
Archit Arora

Reputation: 2626

Turns out, I had not enabled POP/IMAP for my gmail account. Now, everything is working!

Additional Info - When trying to connect to gmail using an external app use the below mentioned guidelines for a successful connection -

  1. Verify that your settings are correct: a) Server is smtp.gmail.com or smtp.googlemail.com b) SSL or TSL is enabled c) Outgoing port is 465, 587, or 25 d) Outgoing server authentication is enabled

  2. Check if antivirus is interfering. Disable antivirus check of outgoing mail.

  3. Run Captcha http://www.google.com/accounts/DisplayUnlockCaptcha

  4. Check if your ISP is blocking Gmail. You may need to use your ISP SMTP server.

  5. In your gmail account, go to settings and enable POP/IMAP.

Note - Before running your app "ping" smtp.gmail.com to check if your machine is able to connect to the gmail server. Also, using command-line run "telnet smtp.gmail.com <port number>" (The port numbers can be 465 , 587 or 25) to check if your machine is able to access through the port.

Upvotes: 2

Related Questions