Java – Send Emails using Gmail SMTP using TLS/SSL

Java program to send email through Gmail SMTP server using TLS or SSL protocols. Also, send plain text emails as well as attachments.

Learn to send emails using the Jakarta Mail API and using the Gmail SMTP Server. We will see the Java examples to send plain text emails as well as emails with attachments.

1. Gmail SMTP Server Details

Google has provided free access to one of its SMTP servers and we can use its Java code to send emails.

  • Gmail SMTP server: smtp.gmail.com
  • Port: 465 (SSL required) / 587 (TLS required)
  • Username: Gmail id
  • Password: The app password

We must create the app password as described in this guide. We cannot use the Gmail password (used to signin in the browser) if we have enabled the 2-factor authentication for the account.

In absense of App password, you will get the “AuthenticationFailedException: 534-5.7.9 Application-specific password required.” error in runtime.

2. Jakarta Mail API

For a typical client application, we need to perform the following steps to send an email:

  • Create a mail message containing the message header and body
  • Create a Session object, which authenticates the user using the Authenticator, and controls access to the message store and transport.
  • Send the message to its recipient list.

3. Maven

Start with adding the following dependencies to the project. Note that the Angus Mail implementation of Jakarta Mail Specification 2.1+ providing a platform-independent and protocol-independent framework to build mail and messaging applications.

<dependency>
  <groupId>jakarta.mail</groupId>
  <artifactId>jakarta.mail-api</artifactId>
  <version>2.1.2</version>
</dependency>

<dependency>
  <groupId>org.eclipse.angus</groupId>
  <artifactId>jakarta.mail</artifactId>
  <version>2.0.1</version>
</dependency>

4. Send an Email with TLS

The EmailSender is a utility class that accepts the message parameters and sends the email to recipients.

import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class EmailSender {

  private static final Properties PROPERTIES = new Properties();
  private static final String USERNAME = "admin@gmail.in";   //change it
  private static final String PASSWORD = "password";   //change it
  private static final String HOST = "smtp.gmail.com";

  static {
    PROPERTIES.put("mail.smtp.host", "smtp.gmail.com");
    PROPERTIES.put("mail.smtp.port", "587");
    PROPERTIES.put("mail.smtp.auth", "true");
    PROPERTIES.put("mail.smtp.starttls.enable", "true");
  }

  public static void sendPlainTextEmail(String from, String to, String subject, List<String> messages, boolean debug) {

    Authenticator authenticator = new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(USERNAME, PASSWORD);
      }
    };

    Session session = Session.getInstance(PROPERTIES, authenticator);
    session.setDebug(debug);

    try {

      // create a message with headers
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(from));
      InternetAddress[] address = {new InternetAddress(to)};
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject(subject);
      msg.setSentDate(new Date());

      // create message body
      Multipart mp = new MimeMultipart();
      for (String message : messages) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setText(message, "us-ascii");
        mp.addBodyPart(mbp);
      }
      msg.setContent(mp);

      // send the message
      Transport.send(msg);

    } catch (MessagingException mex) {
      mex.printStackTrace();
      Exception ex = null;
      if ((ex = mex.getNextException()) != null) {
        ex.printStackTrace();
      }
    }
  }
}

To test the above class, we can invoke the sendPlainTextEmail() method as follows:

import java.util.List;

public class MailTest {

  public static void main(String[] args) {
    
    EmailSender.sendPlainTextEmail("sender@gmail.com", 
        "reciever@gmail.com", 
        "Test Email",
        List.of("Hello", "World"), 
        true);
  }
}

Check the email. You should be able to see the email in your Gmail inbox as follows:

5. Send an Email with SSL

If we do not have TLS support on the server, we can use the SSL support provided in the API. To use SSL, follow these steps:

  • Remove the mail.smtp.starttls.enable property
  • Use port number 465
  • Add SSL support in the properties

The modified properties will be:

static {
    PROPERTIES.put("mail.smtp.host", "smtp.gmail.com");
    PROPERTIES.put("mail.smtp.port", "465");
    PROPERTIES.put("mail.smtp.auth", "true");
    PROPERTIES.put("mail.smtp.socketFactory.port", "465");
    PROPERTIES.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  }

Now we can run the above program with modified properties, and we will again get the email in our inbox.

6. Adding Email Attachments

If we want to add the attachments to the email body, we can use the MimeBodyPart.attachFile() method to attach a file.

MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(new File("path/to/file"));

7. Conclusion

In this example, we saw the Java programs to send emails using the Gmail SMTP server to multiple recipients. Drop me your questions in the comments.

Happy Learning !!

Source Code on Github

Leave a Comment

  1. Hello everyone, could you pls help to send an email using the above code. I am unable to send emails through the above code. Getting following error message. Thanks
    Exception in thread “main” javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Learn more at


    534 5.7.9 https://support.google.com/accounts/answer/185833?visit_id=638615011882718410-3790294334&p=InvalidSecondFactor&rd=1 z13sm22908980pjq.0 - gsmtp

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:947)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:858)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:762)
    at javax.mail.Service.connect(Service.java:342)
    at javax.mail.Service.connect(Service.java:222)
    at com.example.demo.DemoApplication.sendEmail(DemoApplication.java:87)
    at com.example.demo.DemoApplication.main(DemoApplication.java:27)

    Reply
    • If you have enabled 2-factor authentication on your Google account you can’t use your regular password to access Gmail programmatically. You need to generate an app-specific password and use that in place of your actual password.

      Steps:

      Log in to your Google account Go to My Account > Sign-in & Security > App Passwords (Sign in again to confirm it’s you) Scroll down to Select App (in the Password & sign-in method box) and choose Other (custom name) Give this app password a name, e.g. “mailer” Choose to Generate Copy the long generated password and paste it into your code instead of your actual Gmail password.

      Reference: SO Thread

      Reply
  2. You need to connect to your network team regarding this they will give u access on your system to access the there host without any network restrictions.

    Reply
  3. Hi authentication is happening if i run code from my desktop, if i run the same code in server authentication doesn’t happen , even if i send wrong password authentication is success and messages are getting delivered.

    final String username=rb.getString(“username”);
    final String password=rb.getString(“password”);
    final String host =rb.getString(“host”);
    final String port =rb.getString(“port”);
    Properties props = new Properties();
    // props.put(“mail.smtp.starttls.enable”, “false”);
    props.put(“mail.smtp.host”, host);
    props.put(“mail.smtp.user”, username);
    props.put(“mail.smtp.password”, password);
    props.put(“mail.smtp.port”, port);
    props.put(“mail.smtp.auth”, “true”);
    // props.put(“mail.smtp.auth.ntlm.disable”, “false”);
    // props.put(“mail.smtp.auth.mechanisms”, “NTLM”);
    // props.put(“mail.smtp.auth.ntlm.domain”, “testsmtp.com”);
    // props.put(“mail.smtp.ssl.trust”, “false”);
    System.out.println(“properties loaded “);
    Session session = Session.getInstance(props,
    new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, password);
    }
    });

    // Session session = Session.getInstance(props);

    try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(rb.getString(“from”)));

    message.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(rb.getString(“to”)));

    message.setSubject(rb.getString(“subject”));
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(rb.getString(“text”));

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    String filename = rb.getString(“filename”);
    System.out.println(“file is ” + filename);
    DataSource source = new FileDataSource(filename);

    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(source.getName());
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);
    // System.out.println(session.getTransport(“smtp”));
    // Transport transport = session.getTransport(“smtp”);

    // transport.connect(username, password);

    Transport.send(message);

    System.out.println(“Message sent successfully”);
    // transport.close();

    } catch (MessagingException e) {

    System.out.println(“Unable to send message ” + e.getMessage() );

    Reply
  4. Thanks a ton Lokesh and friends who shared…You have helped me a lot. i am very Thankful for this code…God Bless you with great life a ahead

    Reply
  5. I refered above code…but it is giving me following error :
    i changed name of class as SedEmail2.java

    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 586;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
    at javax.mail.Service.connect(Service.java:291)
    at javax.mail.Service.connect(Service.java:172)
    at demo.Emailsend2.sendEmail(Emailsend2.java:74)
    at demo.Emailsend2.main(Emailsend2.java:27)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
    … 5 more
    Java Result: 1

    Reply
  6. Sir,
    I updated my code.after updation eject error mention below.

    Thanks

    run:
    DEBUG: setDebug: JavaMail version 1.5.1
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host “host”, port 25, isSSL false
    com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: host, 25; timeout -1;
    nested exception is:
    java.net.UnknownHostException: host
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1984)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:656)
    at javax.mail.Service.connect(Service.java:345)
    at javax.mail.Service.connect(Service.java:226)
    at maina.MainA.sendMail(MainA.java:92)
    at maina.MainA.main(MainA.java:32)
    Caused by: java.net.UnknownHostException: host
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:158)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:154)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:380)
    at java.net.Socket.connect(Socket.java:569)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:569)
    at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:301)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
    … 5 more
    BUILD SUCCESSFUL (total time: 2 seconds)

    My 32 line and 92 line Coding is:-

    32 line no.) MainA.sendMail(“email”, “password”, “host”, “port”, “true”, “true”, true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,
    “hi baba don’t send virus mails..”,
    “This is my style…of reply..If u send virus mails..”);

    92 line no.) msg.saveChanges();
    Transport transport = session.getTransport(“smtp”);
    transport.connect(host, userName, passWord);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
    return true;
    }
    catch (Exception mex)
    {
    mex.printStackTrace();
    return false;
    }
    }

    Reply
    • This error is thrown to indicate that the IP address of a host could not be determined.
      Find out the IP address of mail server i.e. “blr-outlook.ibm.com” and place that IP directly into “props.put(“mail.smtp.host”, host);”

      Reply
      • Hi,
        Sorry to say sir,but message does not send in email ids.this code used in my personal machine but that is not even running.Please help me.I’ve used editor NetBeans 7.2.and i’m sending my debug after run.

        Thanks

        DEBUG: setDebug: JavaMail version 1.5.1
        DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
        DEBUG SMTP: useEhlo true, useAuth true
        DEBUG SMTP: trying to connect to host “host”, port 25, isSSL false
        BUILD SUCCESSFUL (total time: 3 seconds)

        Reply
        • This code works buddy. Just your machine is not able to resolve hostname. Open windows command prompt. Type “ping blr-outlook.ibm.com”. See if machine is reachable. I believe it will not and will timeout. If you can ping above from command prompt, then ONLY this code will run.

          Reply
          • Hi,
            Finally my code is mention below.I don’t know why is not message send in email ids.
            Please check my code and find my mistake and correct them.I check “ping blr-outlook.ibm.com” in cmd.

            I saw in cmd after enter this blah blah..
            Thanks

            Pinging blr-outlook.ibm.com [11.201.51.251] with 32 bytes of data:
            Reply from 11.201.51.251: bytes=32 time=93ms TTL=119
            Reply from 11.201.51.251: bytes=32 time=76ms TTL=119
            Reply from 11.201.51.251: bytes=32 time=71ms TTL=119
            Reply from 11.201.51.251: bytes=32 time=70ms TTL=119

            Ping statistics for 11.201.51.251:
            Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
            Approximate round trip times in milli-seconds:
            Minimum = 70ms, Maximum = 93ms, Average = 77ms

            /*
            * To change this template, choose Tools | Templates
            * and open the template in the editor.
            */
            package maina;

            import javax.mail.*;
            import javax.mail.internet.*;
            import java.util.*;
            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 MainA
            {
            String d_email = “KA11479G”,
            d_password = “kn@nov2014”,
            d_host = “blr-outlook.ibm.com”,
            d_port = “25”,
            m_to = “kapeesh.gupta@ibm.com”,
            m_subject = “Testing”,
            m_text = “Hey, this is the testing email using blr-outlook.ibm.com”;

            public static void main(String[] args)throws Exception
            {
            String[] to={“kapeesh.gupta@ibm.com”};
            String[] cc={“debarka.sarkar@ibm.com”};
            String[] bcc={“amit.kudale@ibm.com”};
            //This is for google
            MainA.sendMail(“email”, “password”, “host”, “port”, “true”, “true”, true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,
            “hi baba don’t send virus mails..”,
            “This is my style…of reply..If u send virus mails..”);
            }

            public synchronized static boolean sendMail(
            String userName, String passWord, String host,
            String port, String starttls, String auth,
            boolean debug, String socketFactoryClass, String fallback,
            String[] to, String[] cc, String[] bcc,
            String subject, String text)
            {
            Properties props = new Properties();
            //Properties props=System.getProperties();
            props.put(“mail.smtp.user”, userName);
            props.put(“mail.smtp.host”,host);
            if(!””.equals(port)) {
            props.put(“25″, port);
            }
            if(!””.equals(starttls)) {
            props.put(“mail.smtp.starttls.enable”,starttls);
            }
            props.put(“mail.smtp.auth”, auth);
            if(debug) {
            props.put(“mail.smtp.debug”, “true”);
            } else {
            props.put(“mail.smtp.debug”, “false”);
            }
            if(!””.equals(port)) {
            props.put(“mail.smtp.socketFactory.port”, port);
            }
            if(!””.equals(socketFactoryClass)) {
            props.put(“mail.smtp.socketFactory.class”,socketFactoryClass);
            }
            if(!””.equals(fallback)) {
            props.put(“mail.smtp.socketFactory.fallback”, fallback);
            }
            try
            {
            Session smtpSession = Session.getDefaultInstance(props, null);
            smtpSession.setDebug(true);
            MimeMessage msg = new MimeMessage(smtpSession);
            msg.setText(text);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(“kapeesh.gupta@ibm.com”));
            for(int i=0;i<to.length;i++) {
            msg.addRecipient(Message.RecipientType.TO,
            new InternetAddress(to[i]));
            }
            for(int i=0;i<cc.length;i++) {
            msg.addRecipient(Message.RecipientType.CC,
            new InternetAddress(cc[i]));
            }
            for(int i=0;i<bcc.length;i++) {
            msg.addRecipient(Message.RecipientType.BCC,
            new InternetAddress(bcc[i]));
            }
            msg.saveChanges();
            Transport transport = smtpSession.getTransport("smtp");
            transport.connect(host, userName, passWord);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
            }
            catch (Exception mex)
            {
            return false;
            }
            }
            }

          • I edited your code and below is working code. You must have also got an email. As I am not in IBM network, I still have used gmail SMTP. Please change SMTP Host, port, username, password in application and it should work. And from next time, please do not post any password in comments.

            import java.util.Properties;
            
            import javax.mail.Message;
            import javax.mail.Session;
            import javax.mail.Transport;
            import javax.mail.internet.InternetAddress;
            import javax.mail.internet.MimeMessage;
            
            public class MainA 
            {
            	public static void main(String[] args) throws Exception {
            		String[] to = { &quot;kapeesh.gupta@ibm.com&quot; };
            		String[] cc = { &quot;debarka.sarkar@ibm.com&quot; };
            		String[] bcc ={ &quot;amit.kudale@ibm.com&quot; };
            		// This is for google
            		MainA.sendMail(&quot;lokeshgupta1981@gmail.com&quot;, &quot;**********&quot;, &quot;smtp.gmail.com&quot;, &quot;25&quot;, &quot;true&quot;, &quot;true&quot;,
            				true, &quot;javax.net.ssl.SSLSocketFactory&quot;, &quot;false&quot;, to, cc, bcc,
            				&quot;hi baba don’t send virus mails..&quot;,
            				&quot;This is my style…of reply..If u send virus mails..&quot;);
            	}
            
            	public synchronized static boolean sendMail(String userName,
            			String passWord, String host, String port, String starttls,
            			String auth, boolean debug, String socketFactoryClass,
            			String fallback, String[] to, String[] cc, String[] bcc,
            			String subject, String text) {
            		Properties props = new Properties();
            		props.put(&quot;mail.smtp.user&quot;, userName);
            		props.put(&quot;mail.smtp.host&quot;, host);
            		props.put(&quot;port&quot;, port);
            		props.put(&quot;mail.smtp.starttls.enable&quot;, starttls);
            		props.put(&quot;mail.smtp.auth&quot;, auth);
            		if (debug) {
            			props.put(&quot;mail.smtp.debug&quot;, &quot;true&quot;);
            		} else {
            			props.put(&quot;mail.smtp.debug&quot;, &quot;false&quot;);
            		}
            		try {
            			Session smtpSession = Session.getDefaultInstance(props, null);
            			smtpSession.setDebug(true);
            			MimeMessage msg = new MimeMessage(smtpSession);
            			msg.setText(text);
            			msg.setSubject(subject);
            			msg.setFrom(new InternetAddress(&quot;lokeshgupta1981@gmail.com&quot;));
            			for (int i = 0; i &lt; to.length; i++) {
            				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
            						to[i]));
            			}
            			for (int i = 0; i &lt; cc.length; i++) {
            				msg.addRecipient(Message.RecipientType.CC, new InternetAddress(
            						cc[i]));
            			}
            			for (int i = 0; i &lt; bcc.length; i++) {
            				msg.addRecipient(Message.RecipientType.BCC,
            						new InternetAddress(bcc[i]));
            			}
            			msg.saveChanges();
            			Transport transport = smtpSession.getTransport(&quot;smtp&quot;);
            			transport.connect(host, userName, passWord);
            			transport.sendMessage(msg, msg.getAllRecipients());
            			transport.close();
            			return true;
            		} catch (Exception mex) {
            			mex.printStackTrace();
            			System.out.println(mex.getLocalizedMessage());
            			return false;
            		}
            	}
            }
            

            Output:

            DEBUG: setDebug: JavaMail version 1.5.2
            DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
            DEBUG SMTP: useEhlo true, useAuth true
            DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 25, isSSL false
            220 mx.google.com ESMTP wk2sm5328789pac.12 – gsmtp
            DEBUG SMTP: connected to host “smtp.gmail.com”, port: 25

            EHLO 192.168.2.6
            250-mx.google.com at your service, [14.102.107.130]
            250-SIZE 35882577
            250-8BITMIME
            250-STARTTLS
            250-ENHANCEDSTATUSCODES
            250-PIPELINING
            250-CHUNKING
            250 SMTPUTF8
            DEBUG SMTP: Found extension “SIZE”, arg “35882577”
            DEBUG SMTP: Found extension “8BITMIME”, arg “”
            DEBUG SMTP: Found extension “STARTTLS”, arg “”
            DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
            DEBUG SMTP: Found extension “PIPELINING”, arg “”
            DEBUG SMTP: Found extension “CHUNKING”, arg “”
            DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
            STARTTLS
            220 2.0.0 Ready to start TLS
            EHLO 192.168.2.6
            250-mx.google.com at your service, [14.102.107.130]
            250-SIZE 35882577
            250-8BITMIME
            250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN
            250-ENHANCEDSTATUSCODES
            250-PIPELINING
            250-CHUNKING
            250 SMTPUTF8
            DEBUG SMTP: Found extension “SIZE”, arg “35882577”
            DEBUG SMTP: Found extension “8BITMIME”, arg “”
            DEBUG SMTP: Found extension “AUTH”, arg “LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN”
            DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
            DEBUG SMTP: Found extension “PIPELINING”, arg “”
            DEBUG SMTP: Found extension “CHUNKING”, arg “”
            DEBUG SMTP: Found extension “SMTPUTF8”, arg “”
            DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
            DEBUG SMTP: AUTH LOGIN command trace suppressed
            DEBUG SMTP: AUTH LOGIN succeeded
            DEBUG SMTP: use8bit false
            MAIL FROM:
            250 2.1.0 OK wk2sm5328789pac.12 – gsmtp
            RCPT TO:
            250 2.1.5 OK wk2sm5328789pac.12 – gsmtp
            RCPT TO:
            250 2.1.5 OK wk2sm5328789pac.12 – gsmtp
            RCPT TO:
            250 2.1.5 OK wk2sm5328789pac.12 – gsmtp
            DEBUG SMTP: Verified Addresses
            DEBUG SMTP: kapeesh.gupta@ibm.com
            DEBUG SMTP: debarka.sarkar@ibm.com
            DEBUG SMTP: amit.kudale@ibm.com
            DATA
            354 Go ahead wk2sm5328789pac.12 – gsmtp
            From: lokeshgupta1981@gmail.com
            To: kapeesh.gupta@ibm.com
            Cc: debarka.sarkar@ibm.com
            Message-ID: <12869066.0.1419089528207.JavaMail.user@user-PC>
            Subject: =?Cp1252?Q?hi_baba_don=92t_send_virus_mails..?=
            MIME-Version: 1.0
            Content-Type: text/plain; charset=Cp1252
            Content-Transfer-Encoding: quoted-printable

            This is my style=85of reply..If u send virus mails..
            .
            250 2.0.0 OK 1419089555 wk2sm5328789pac.12 – gsmtp
            QUIT
            221 2.0.0 closing connection wk2sm5328789pac.12 – gsmtp

          • Hello Sir,
            This time eject error in my code.username and password not accepted.Please tell me and sorry for disturbing.
            Why userName and password not accepted while i entered correct gmail id or password.Still my entries are wrong.Why??

            Line no.21 and Line no.64.are mention below.

            21) MainA.sendMail(“kapeesh1@gmail.com”, “*****”, “smtp.gmail.com”, “25”, “true”, “true”,
            true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,

            64) transport.connect(host,userName,passWord);

            Thanks

            DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
            DEBUG SMTP: AUTH LOGIN command trace suppressed
            DEBUG SMTP: AUTH LOGIN failed
            javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
            535 5.7.8 https://support.google.com/mail/answer/7126229?visit_id=637442894384312704-1021204172&rd=1#cantsignin c9sm14915179pdj.52 – gsmtp

            535-5.7.8 Username and Password not accepted. Learn more at
            535 5.7.8 https://support.google.com/mail/answer/7126229?visit_id=637442894384312704-1021204172&rd=1#cantsignin c9sm14915179pdj.52 – gsmtp

            at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:892)
            at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:814)
            at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:728)
            at javax.mail.Service.connect(Service.java:364)
            at javax.mail.Service.connect(Service.java:245)
            at maina.MainA.sendMail(MainA.java:64)
            at maina.MainA.main(MainA.java:21)
            BUILD SUCCESSFUL (total time: 13 seconds)

          • Hi,
            No problem sir,But u have a lot more done.Thank u so much.
            But sir mainly prob in these 2 lines only.and why could not convert socket to TLS???

            1) MainA.sendMail(“kapeesh1@gmail.com”, “********”, “smtp.gmail.com”, 25, “true”, “true”,
            true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,
            “hi baba don’t send virus mails..”,
            “This is my style…of reply..If u send virus mails..”);

            2) transport.connect(host, userName, passWord);

            3) javax.mail.MessagingException: Could not convert socket to TLS;

            Thanks

  7. Hello sir,
    Please give me right code.

    My error found is:-

    debug:
    java.lang.NoClassDefFoundError: sendmail/SendMail
    Caused by: java.lang.ClassNotFoundException: sendmail.SendMail
    at java.net.URLClassLoader$1.run(URLClassLoader.java:220)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:209)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:208)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:325)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:270)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:338)
    Error: Could not find the main class sendmail.SendMail.
    Error: A JNI error has occurred, please check your installation and try again
    Exception in thread “main” Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

    Reply
      • Hello Sir,
        Thanks for give me answer.sir my code perfectly run in my system but message does not send in mail ids.

        Please see this output.and find my mistake and tell me.

        Thanks

        DEBUG: JavaMail version 1.5.1
        DEBUG: URL jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.providers
        DEBUG: successfully loaded resource: jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.providers
        DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
        DEBUG: Tables of loaded providers
        DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
        DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
        DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
        DEBUG: URL jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.address.map
        DEBUG: successfully loaded resource: jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.address.map
        DEBUG: setDebug: JavaMail version 1.5.1
        DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
        DEBUG SMTP: need username and password for authentication
        DEBUG SMTP: useEhlo true, useAuth true
        DEBUG SMTP: trying to connect to host “smtp.ibm.com”, port 25, isSSL false
        Oops something has gone pearshaped!
        com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.ibm.com, 25; timeout -1;
        nested exception is:
        java.net.UnknownHostException: smtp.ibm.com
        BUILD SUCCESSFUL (total time: 2 seconds)

        Reply
          • Hi,
            I discussed with admin.He told me,our Port no is “25”,Host Name is “blr-outlook.ibm.com”,userName-“KA11479G”,but message does not send in mail id.i m sending my code please see my code and find errors.And send me correct code.

            Thanks

            import javax.mail.*;
            import javax.mail.internet.*;
            import java.util.*;
            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 Main1
            {
            String d_email = “KA11479G”,
            d_password = “kn@nov2014”,
            d_host = “blr-outlook.ibm.com”,
            d_port = “25”,
            m_to = “kapeesh.gupta@ibm.com”,
            m_subject = “Testing”,
            m_text = “Hey, this is the testing email using blr-outlook.ibm.com”;
            public static void main(String[] args)
            {
            String[] to={“kapeesh.gupta@ibm.com”};
            String[] cc={“debarka.sarkar@ibm.com”};
            String[] bcc={“amit.kudale@ibm.com”};
            //This is for google
            Main1.sendMail(“email”, “password”, “host”, “port”, “true”, “true”, true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,
            “hi baba don’t send virus mails..”,
            “This is my style…of reply..If u send virus mails..”);
            }

            public synchronized static boolean sendMail(
            String userName, String passWord, String host,
            String port, String starttls, String auth,
            boolean debug, String socketFactoryClass, String fallback,
            String[] to, String[] cc, String[] bcc,
            String subject, String text)
            {
            Properties props = new Properties();
            //Properties props=System.getProperties();
            props.put(“mail.smtp.user”, userName);
            props.put(“mail.smtp.host”, host);
            if(!””.equals(port)) {
            props.put(“mail.smtp.port”, port);
            }
            if(!””.equals(starttls)) {
            props.put(“mail.smtp.starttls.enable”,starttls);
            }
            props.put(“mail.smtp.auth”, auth);
            if(debug) {
            props.put(“mail.smtp.debug”, “true”);
            } else {
            props.put(“mail.smtp.debug”, “false”);
            }
            if(!””.equals(port)) {
            props.put(“mail.smtp.socketFactory.port”, port);
            }
            if(!””.equals(socketFactoryClass)) {
            props.put(“mail.smtp.socketFactory.class”,socketFactoryClass);
            }
            if(!””.equals(fallback)) {
            props.put(“mail.smtp.socketFactory.fallback”, fallback);
            }

            try
            {
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(text);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(“blr-outlook.ibm.com”));
            for(int i=0;i<to.length;i++) {
            msg.addRecipient(Message.RecipientType.TO,
            new InternetAddress(to[i]));
            }
            for(int i=0;i<cc.length;i++) {
            msg.addRecipient(Message.RecipientType.CC,
            new InternetAddress(cc[i]));
            }
            for(int i=0;i<bcc.length;i++) {
            msg.addRecipient(Message.RecipientType.BCC,
            new InternetAddress(bcc[i]));
            }
            msg.saveChanges();
            Transport transport = session.getTransport("smtp");
            transport.connect(host, userName, passWord);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
            }
            catch (Exception mex)
            {
            return false;
            }
            }

            }

          • Hi,
            I changed this,code is perfectly run but message does not send email ids.Debug is below here.

            Thanks

            DEBUG: setDebug: JavaMail version 1.5.1
            DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
            DEBUG SMTP: useEhlo true, useAuth true
            DEBUG SMTP: trying to connect to host “host”, port 25, isSSL false
            BUILD SUCCESSFUL (total time: 2 seconds)

          • In your catch block, before returning false, plz print/log the error as well.

            catch (Exception mex)
            {
            mex.printStackTrace(); //OR Log it
            return false;
            }

            It will show you why mail is not sent.

  8. Hi Lokesh,

    I have been facing an issue with javamail sending a mail from gmail. Actually i need to send it from an smtp server starting with 10.x.x.x using port 25. My Environment is jdk 1.7/windows7 32bit/javamail 1.4.1.

    Sample Code

    String to = "foo@bar.com";//change accordingly
    
            // Sender's email ID needs to be mentioned
            String from = "example@gmail.com";//change accordingly
            
    
            // Assuming you are sending email through relay.jangosmtp.net
            String host = "10.x.x.x";
    
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.port", "25");
            props.put("mail.debug","true");
    
            // Get the Session object.
            Session session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                        }
                    });
    
            try {
                // Create a default MimeMessage object.
                Message message = new MimeMessage(session);
    
                // Set From: header field of the header.
                message.setFrom(new InternetAddress(from));
    
                // Set To: header field of the header.
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(to));
    
                // Set Subject: header field
                message.setSubject("Testing Subject");
    
                // Now set the actual message
                message.setText("Hello,");
    
                // Send message
                Transport.send(message);
    
                System.out.println("Sent message successfully....");
    
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
    

    java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: 10.x.x.x, port: 25;
    nested exception is:
    java.net.SocketException: Permission denied: connect
    at
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)
    at org.testng.SuiteRunner.run(SuiteRunner.java:254)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:125)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: 10.x.x.x, port: 25;
    nested exception is:
    java.net.SocketException: Permission denied: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
    at javax.mail.Service.connect(Service.java:310)
    at javax.mail.Service.connect(Service.java:169)
    at javax.mail.Service.connect(Service.java:118)
    at javax.mail.Transport.send0(Transport.java:188)
    at javax.mail.Transport.send(Transport.java:118)
    at
    … 30 more
    Caused by: java.net.SocketException: Permission denied: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
    … 37 more

    Remedies Taken:
    – I have unchecked ipv6 in Network and connections.
    – i have added preferipv4stack property also not worked.
    Notes:
    when i have used smtp.gmail.com as host and port as 587 it is working fine. but my task is to send a mail through 10.x.x.x smtp server.
    Please help me Lokesh.
    Thanks in advance.

    Reply
  9. Exception in thread “main” com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.gmail.com, 586; timeout -1;
    nested exception is:
    java.net.ConnectException: Connection refused

    How to resolve this problem..plaese help!!!

    Reply
  10. hello sir,,,

    I am getting this error…how can I get rid of it…
    pls help me on this…

    I used both 468 and 586 ports…but the error is same…
    ————————————————————————————–
    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 586;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    at javax.mail.Service.connect(Service.java:295)
    at javax.mail.Service.connect(Service.java:176)
    at one.Chjhkj.sendEmail(Chjhkj.java:69)
    at one.Chjhkj.main(Chjhkj.java:22)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    … 5 more
    ————————————————————————————–

    Reply
  11. hey when i copy paste this code and change the userid and password in netbeans i am getting following exception please help me out….
    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 586;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
    at javax.mail.Service.connect(Service.java:295)
    at javax.mail.Service.connect(Service.java:176)
    at JavaEmail.sendEmail(JavaEmail.java:67)
    at JavaEmail.main(JavaEmail.java:20)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    … 5 more

    Reply
    • Manjeet, Can you please tell me the exact error [stack trace].. FYI: above program runs fine on my home network.
      Also, please ensure two things before running this program.
      1) You are not behind any firewall. [Most corporate networks have them. e.g. in offices]
      2) Put correct credentials here: [i.e. your email and password]

      String fromUser = “user-email@gmail.com”;
      String fromUserEmailPassword = “*******”;

      Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.