Send email using JavaMail API and your Gmail account

Hi folks! For your convenience, I’ve hosted the source code for this article at GitHub. Please feel free to try out that code and drop me a line if you get any queries. You can access the repository here.

Sending email using Java is not a difficult task and it’s just about writing few lines of codes. But when you are writing such an application, you’ll end up with lot of exceptions obviously. There are lots of reasons for that, but as my opinion, wrong email configuration settings would cause the exceptions.

If you need to write a Java application to send an email, you need an outgoing mail server such as SMTP (Simple Mail Transfer Protocol) server. There are many SMTP servers out there, but in order to send an email most servers require authentication (You have to have an account in your SMTP server and you must know account credentials). There exist free SMTP servers without authentication, but I’m not sure about their reliability and Quality of Service (QoS).

At the authentication process, most developers fail due to bad configurations. There are several configuration settings should be set in your code, before you submit the message to the SMTP server.

To demonstrate this settings, I’ll create a Java application from the scratch and it will use Gmail as the outgoing SMTP server (You can use any SMTP server with valid credentials. But here I used Gmail because I’m addicted to Google!).

You can download the complete source code and required libraries here. I developed it using NetBeans IDE, but you can use any IDE to proceed.

Prerequisites

Source Code

package com.dunithd.jmail;

import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage.RecipientType;

import java.util.*;

/**
 * Simple Class to send an email using JavaMail API (javax.mail) and Gmail SMTP server
 * @author Dunith Dhanushka, dunithd@gmail.com
 * @version 1.0
 */
public class GmailSender {

    private static String HOST = "smtp.gmail.com";
    private static String USER = "your_username@gmail.com";
    private static String PASSWORD = "put_your_password_here";
    private static String PORT = "465";
    private static String FROM = "put_from_address_here";
    private static String TO = "put_to_address_here";

    private static String STARTTLS = "true";
    private static String AUTH = "true";
    private static String DEBUG = "true";
    private static String SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static String SUBJECT = "Testing JavaMail API";
    private static String TEXT = "This is a test message from my java application. Just ignore it";

    public static synchronized void send() {
        //Use Properties object to set environment properties
        Properties props = new Properties();

        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.user", USER);

        props.put("mail.smtp.auth", AUTH);
        props.put("mail.smtp.starttls.enable", STARTTLS);
        props.put("mail.smtp.debug", DEBUG);

        props.put("mail.smtp.socketFactory.port", PORT);
        props.put("mail.smtp.socketFactory.class", SOCKET_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        try {

            //Obtain the default mail session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(true);

            //Construct the mail message
            MimeMessage message = new MimeMessage(session);
            message.setText(TEXT);
            message.setSubject(SUBJECT);
            message.setFrom(new InternetAddress(FROM));
            message.addRecipient(RecipientType.TO, new InternetAddress(TO));
            message.saveChanges();

            //Use Transport to deliver the message
            Transport transport = session.getTransport("smtp");
            transport.connect(HOST, USER, PASSWORD);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
       GmailSender.send();
       System.out.println("Mail sent successfully!");
    }
}

When writing the application, you have to set some Environment Properties that are used by the JavaMail APIs. The JavaMail javadocs contain additional information on properties supported by JavaMail.

You can use java.util.Properties class to set these properties.

  • mail.smtp.host: Specifies the protocol-specific default Mail server. In your application, set this property to smtp.gmail.com
  • mail.smtp.user: Specifies the protocol-specific default username for connecting to the Mail server. In your application, set this property to your Gmail username.
  • mail.smtp.auth: Specifies whether host requires authentication or not. In our application, set this property to true.
  • mail.smtp.debug: Specifies the initial debug mode. Setting this property to true will turn on debug mode, while setting it to false turns debug mode off. If you need deeper diagnosis, set this to true.
  • mail.smtp.port: Specifies the port that is used by SMTP server. In your application, set this to 465.
  • mail.smtp.starttls.enable: This is the most important one. If you miss this, you’ll definitely get an error. Most SMTP servers support SSL (Secure Socket Layer) connections which can be used for secure login to the server. They use STARTTLS command (see RFC 2487 and RFC 3501) to switch the connection to be secured by TLS.
    Use of the STARTTLS command is preferred in cases where the server supports both SSL and non-SSL connections. This SSL/TLS support in JavaMail works only when JavaMail is used on a version of J2SE that includes SSL support.
    The STARTTLS support is available in the standard “IMAP” and “SMTP” protocols, but must be enabled by setting the appropriate property, mail.imap.starttls.enable or mail.smtp.starttls.enable, to “true”. When set, if the server supports the STARTTLS command, it will be used after making the connection and before sending any login information.

If everything goes fine, you’ll see an output like this.

Output of the application

Output of the application

Notes

This application cannot be used in a network that uses a proxy server. You must have a direct connection to the internet otherwise you’ll get UnknownHostException.

UnknownHostException

UnknownHostException

In my next post, I’m gonna explain you how to send an email with an attachment.

About these ads

88 thoughts on “Send email using JavaMail API and your Gmail account

  1. Pingback: Send E-mail with attachments using JavaMail « Dunith Dhanushka's Weblog

    • How do you enforce TLS? For instance, when you set mail.smtp.starttls.enable to “true” it will use the secure connection, if it’s available. Otherwise, it just sends unsecure. How do I make it so that it only sends if TLS connection is available?

    • Hey Arthur,
      That can be done in this way…
      first, change the TO string to contain your recipient addresses. Just concatenate the addresses with comma and a space
      eg: String TO = “john@gmail.com, arthur@gmail.com, foo@ymail.com“;

      Then replace the method message.addRecipient() with this(see line number 57)

      message.addRecipients(RecipientType.TO, TO);

      Thats it and you are done!

  2. I am trying to call your program in JSP page using following code.but it gives the error

    JSP Page

    Hello World!

    it gives me following output in netbeans 6.8
    Hello World!
    com.myapp.struts.GmailSender@357bdf

  3. it gives me following error in eclipse
    org.apache.jasper.JasperException: /page4.jsp(6,1) Page directive: illegal to have multiple occurrences of contentType with different values (old: text/html; charset=ISO-8859-1, new: text/html)
    org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
    org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:236)
    org.apache.jasper.compiler.Validator$DirectiveVisitor.visit(Validator.java:132)
    org.apache.jasper.compiler.Node$PageDirective.accept(Node.java:608)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
    org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
    org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    org.apache.jasper.compiler.Validator.validateDirectives(Validator.java:1723)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:182)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:347)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.29 logs.

  4. Good article..please keep it…but when i sent mail to yahoo it goes to spam folder.. Plz help how to resolve..
    i just modify Transport transport = session.getTransport(“smtp”); to
    Transport transport = session.getTransport(“smtps”);

  5. thanks for ur article u solved a big problem for me i appreciate that but please i wanna send a link in the email how i can do it??!! and thanks a lot :)

    • Adding a hyper link is a not a difficult task in JavaMail.
      Say for example you want to insert a link to http://www.google.com.

      Then all you have to do is place the necessary HTML in a String.
      Eg: Visit Google

      Note that do the String escaping.

      since you are using java.mail, you should set the text this way:

      message.setText(body, "UTF-8", "html");

      thanks

  6. i`ve got this error

    DEBUG: setDebug: JavaMail version 1.4.4
    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 “smtp.gmail.com”, port 465, isSSL false
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.SocketException: Connection reset
    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)
    ………………..

    what should i do ?

    thx for advice

    • Seems like you are having a network issue that prevents you from connecting to the Google’s SMTP server. Please check your proxy settings and adjust them accordingly.

      • i’ve got the same error… im not using proxy… im using 3g connection.
        what should i do to solve this problem?

  7. Hi, I apriciate your article, but i got this error: 530 5.7.0 Must issue a STARTTLS command first. f17sm709927ani.25, could you help me?, please, thanks a lot

  8. Hi Everybody,

    I have very complicated requirement.. Please share your thoughts on this..
    In a java application, users has to register themeless with their email ids (could be gmail, yahoo or any other).. After registration and login, they can perform some of the activities. In a particular activity user will be accepting certain conditions by clicking a button and an email should be sent from java application.. The twist here is email should go directly from registered user gmail, yahoo or any other email ids to concerned party… i.e. after clicking a button in the java application, registered user should have the mail that has been sent from java application in their Sent Mail box ( like gmail, yahoo or any other).. Something like the registered user logging into his gmail account and sending an email..

    Please need help on this..

    Rgds,
    Ramachandran

  9. Dear I am having javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first error when I am trying to send a mail from my office. But is is working fine with my office PC.
    Should I change any setting in my home PC regarding STARTTLS.
    Please let me know what should I do?

  10. Hi, I apriciate your article, but i got this error: 530 5.7.0 Must issue a STARTTLS command first. f17sm709927ani.25, could you help me?, please, thanks a lot

  11. package com.mail;

    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.mail.internet.MimeMessage.RecipientType;

    import java.util.*;

    public class GmailSender {

    private static String HOST = “smtp.gmail.com”;
    private static String USER = “XXXXX@gmail.com”;
    private static String PASSWORD = “**********”;
    private static String PORT = “465”;
    private static String FROM = “XXXXXX@gmail.com”;
    private static String TO = “XXXXXXX@gmail.com”;

    private static String STARTTLS = “true”;
    private static String AUTH = “true”;
    private static String DEBUG = “true”;
    private static String SOCKET_FACTORY = “javax.net.ssl.SSLSocketFactory”;
    private static String SUBJECT = “Testing JavaMail API”;
    private static String TEXT = “This is a test message from my java application. Just ignore it”;

    public static synchronized boolean send() {
    // Use Properties object to set environment properties
    Properties props = new Properties();

    props.put(“mail.smtp.host”, HOST);
    props.put(“mail.smtp.port”, PORT);
    props.put(“mail.smtp.user”, USER);

    props.put(“mail.smtp.auth”, AUTH);
    props.put(“mail.smtp.starttls.enable”, STARTTLS);
    props.put(“mail.smtp.debug”, DEBUG);

    props.put(“mail.smtp.socketFactory.port”, PORT);
    props.put(“mail.smtp.socketFactory.class”, SOCKET_FACTORY);
    props.put(“mail.smtp.socketFactory.fallback”, “false”);

    try {

    // Obtain the default mail session
    Session session = Session.getInstance(props,
    new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(USER, PASSWORD);
    }
    });

    session.setDebug(true);

    // Construct the mail message
    MimeMessage message = new MimeMessage(session);
    message.setText(TEXT);
    message.setSubject(SUBJECT);
    message.setFrom(new InternetAddress(FROM));
    message.addRecipient(RecipientType.TO, new InternetAddress(TO));
    message.saveChanges();

    // Use Transport to deliver the message
    Transport transport = session.getTransport(“smtp”);
    transport.connect(HOST, USER, PASSWORD);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();

    } catch (Exception e) {
    e.printStackTrace();
    return false;
    }
    return true;
    }

    public static void main(String[] args) {
    boolean flag = GmailSender.send();
    if (flag) {
    System.out.println(“Mail sent successfully!”);
    } else {
    System.out.println(“Mail not sent!”);
    }
    }
    }

    the above code gives the below Exception… can any one help me to resolve this issue please…….

    DEBUG: setDebug: JavaMail version 1.4.4
    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 “smtp.gmail.com”, port 465, isSSL false
    220 mx.google.com ESMTP kt2sm4702869pbc.73
    DEBUG SMTP: connected to host “smtp.gmail.com”, port: 465

    EHLO desktop
    250-mx.google.com at your service, [183.82.97.186]
    250-SIZE 35882577
    250-8BITMIME
    250-AUTH LOGIN PLAIN XOAUTH
    250-ENHANCEDSTATUSCODES
    250 PIPELINING
    DEBUG SMTP: Found extension “SIZE”, arg “35882577”
    DEBUG SMTP: Found extension “8BITMIME”, arg “”
    DEBUG SMTP: Found extension “AUTH”, arg “LOGIN PLAIN XOAUTH”
    DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
    DEBUG SMTP: Found extension “PIPELINING”, arg “”
    DEBUG SMTP: Attempt to authenticate
    DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
    AUTH LOGIN
    334 VXNlcm5hbWU6
    c3VkaGFrYXIua2FpdGhlcGFsbGlAZ21haWwuY29t
    334 UGFzc3dvcmQ6
    ODEyMTMxNTI0MA==
    535-5.7.1 Application-specific password required. Learn more at
    535 5.7.1 http://support.google.com/accounts/bin/answer.py?answer=185833 kt2sm4702869pbc.73
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL false
    220 mx.google.com ESMTP ka9sm4706755pbb.59
    DEBUG SMTP: connected to host “smtp.gmail.com”, port: 465

    EHLO desktop
    250-mx.google.com at your service, [183.82.97.186]
    250-SIZE 35882577
    250-8BITMIME
    250-AUTH LOGIN PLAIN XOAUTH
    250-ENHANCEDSTATUSCODES
    250 PIPELINING
    DEBUG SMTP: Found extension “SIZE”, arg “35882577”
    DEBUG SMTP: Found extension “8BITMIME”, arg “”
    DEBUG SMTP: Found extension “AUTH”, arg “LOGIN PLAIN XOAUTH”
    DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
    DEBUG SMTP: Found extension “PIPELINING”, arg “”
    DEBUG SMTP: Attempt to authenticate
    DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
    AUTH LOGIN
    334 VXNlcm5hbWU6
    c3VkaGFrYXIua2FpdGhlcGFsbGlAZ21haWwuY29t
    334 UGFzc3dvcmQ6
    ODEyMTMxNTI0MA==
    535-5.7.1 Application-specific password required. Learn more at
    535 5.7.1 http://support.google.com/accounts/bin/answer.py?answer=185833 ka9sm4706755pbb.59
    javax.mail.AuthenticationFailedException: 535-5.7.1 Application-specific password required. Learn more at
    535 5.7.1 http://support.google.com/accounts/bin/answer.py?answer=185833 ka9sm4706755pbb.59
    Mail not sent!

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at com.mail.GmailSender.send(GmailSender.java:63)
    at com.mail.GmailSender.main(GmailSender.java:75)

    • “535-5.7.1 Application-specific password required. Learn more at…”
      Later Google has updated their security policies to support two step authentication. Because of that Google treats this code as seperate application and it requires application specific password.
      Login to you gmail account, go to Account -> Security and edit Authorizing applications and sites to provide a password for this script.

  12. can you help me?

    This is the configuration of my outlook client however i can´t connect

    Nombre de servidor: pod51011.outlook.com
    Puerto: 587

    javax.mail.MessagingException: Could not connect to SMTP host: pod51011.outlook.com, port: 587
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:855)

    Tanks

      • the account is created with all permissions

        DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
        DEBUG SMTP: useEhlo true, useAuth true

        DEBUG: SMTPTransport trying to connect to host “pod51011.outlook.com”, port 587

        DEBUG SMTP RCVD: 220 pod51011.outlook.com Microsoft ESMTP MAIL Service ready at Fri, 15 Feb 2013 18:32:20 +0000

        DEBUG: SMTPTransport connected to host “pod51011.outlook.com”, port: 587

        DEBUG SMTP SENT: EHLO SECTECSISTEMAS
        DEBUG SMTP RCVD: 250-pod51011.outlook.com Hello [189.203.229.110]
        250-SIZE 36700160
        250-PIPELINING
        250-DSN
        250-ENHANCEDSTATUSCODES
        250-STARTTLS
        250-AUTH
        250-8BITMIME
        250-BINARYMIME
        250 CHUNKING

        DEBUG SMTP Found extension “SIZE”, arg “36700160”
        DEBUG SMTP Found extension “PIPELINING”, arg “”
        DEBUG SMTP Found extension “DSN”, arg “”
        DEBUG SMTP Found extension “ENHANCEDSTATUSCODES”, arg “”
        DEBUG SMTP Found extension “STARTTLS”, arg “”
        DEBUG SMTP Found extension “AUTH”, arg “”
        DEBUG SMTP Found extension “8BITMIME”, arg “”
        DEBUG SMTP Found extension “BINARYMIME”, arg “”
        DEBUG SMTP Found extension “CHUNKING”, arg “”
        DEBUG SMTP: Attempt to authenticate
        DEBUG SMTP: use8bit false
        DEBUG SMTP SENT: MAIL FROM:
        DEBUG SMTP RCVD: 530 5.7.1 Client was not authenticated

        javax.mail.MessagingException: 530 5.7.1 Client was not authenticated

        at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:879)
        at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:599)
        at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:319)
        at mx.gob.sefiplan.Pruebas.GmailSender.send(GmailSender.java:63)
        at mx.gob.sefiplan.Pruebas.GmailSender.main(GmailSender.java:73)

  13. Right here is the perfect web site for anyone who really wants to
    find out about this topic. You realize a whole lot its
    almost hard to argue with you (not that I really would want to…HaHa).
    You definitely put a new spin on a subject that has been written about for decades.
    Great stuff, just wonderful!

  14. The code works well.. But ive tried it in jsp using Beans.. There is a small issue in this.. I didn get any mail when i give it in html..

  15. i am getting the error

    javax.mail.NoSuchProviderException: smtp
    at javax.mail.Session.getService(Session.java:784)
    at javax.mail.Session.getTransport(Session.java:720)
    at javax.mail.Session.getTransport(Session.java:660)
    at javax.mail.Session.getTransport(Session.java:640)
    at com.sample.dao.emailTry.send(emailTry.java:60)
    at com.sample.dao.emailTry.main(emailTry.java:72)

    plz tell me how to solve it

  16. hello…plz send me the source code of send email with attachment….its important n urgent..thanks
    id:bhoomigolaviya@gmail.com

  17. whats the solution of this lots of errors….anyone have d solution plzz suggest me….

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1963)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    at javax.mail.Service.connect(Service.java:345)
    at javax.mail.Service.connect(Service.java:226)
    at filetransfer.Main.sendmessage(Main.java:74)
    at filetransfer.NewJFrame.sendActionPerformed(NewJFrame.java:196)
    at filetransfer.NewJFrame.access$200(NewJFrame.java:21)
    at filetransfer.NewJFrame$3.actionPerformed(NewJFrame.java:83)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6290)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
    at java.awt.Component.processEvent(Component.java:6055)
    at java.awt.Container.processEvent(Container.java:2039)
    at java.awt.Component.dispatchEventImpl(Component.java:4653)
    at java.awt.Container.dispatchEventImpl(Container.java:2097)
    at java.awt.Component.dispatchEvent(Component.java:4481)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4575)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4236)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4166)
    at java.awt.Container.dispatchEventImpl(Container.java:2083)
    at java.awt.Window.dispatchEventImpl(Window.java:2482)
    at java.awt.Component.dispatchEvent(Component.java:4481)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:648)
    at java.awt.EventQueue.access$000(EventQueue.java:84)
    at java.awt.EventQueue$1.run(EventQueue.java:607)
    at java.awt.EventQueue$1.run(EventQueue.java:605)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$2.run(EventQueue.java:621)
    at java.awt.EventQueue$2.run(EventQueue.java:619)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:618)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1731)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:925)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1170)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1197)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1181)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:528)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:333)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    … 43 more
    Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)
    at sun.security.validator.Validator.validate(Validator.java:218)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1185)
    … 54 more
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)
    … 60 more

  18. i have got this error

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:

    how can i solve it?

  19. MUCHAS GRACIAS EL PROBLEMA DE :

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:

    ES DEBIDO A EL ANTIVIRUS O EL FIREWALL REVISAR O DESABILITAR
    FUNCIONA PERFECTO!!

  20. I am trying to implement a same code..but getting a error it may be tls/ssl error of cannot convert socket to tls..no target found..cud u resolve the certificate issue.

  21. Hi, i appreciate you code but when run it, i get lots of erroring :
    DEBUG: setDebug: JavaMail version 1.5.1
    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 465, isSSL false
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    Mail sent successfully!
    nested exception is:
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1986)
    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 project.Sendemail.send(Sendemail.java:58)
    at project.Sendemail.main(Sendemail.java:69)
    Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:541)
    at sun.security.ssl.InputRecord.read(InputRecord.java:374)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:532)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:337)
    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: 1 second)

    I am not quite sure what it means and was wondering if you can help out. Thanks

    • Hi Jex,

      This is due to the fact that you are talking to an HTTP server, not an HTTPS server. Did you use the correct port number for HTTPS?

      Regards,
      Dunith

  22. hi Dunith,
    Primarily Thanks for sharing this knowledge.
    But i am getting some Error like this

    In your code i just changed the name of the class
    and Login Credentials only
    I hope this is not affected to this error

    ——————————————————
    Output in Netbeans :::::::::::
    ——————————————————-
    DEBUG: setDebug: JavaMail version 1.4.7
    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 465, isSSL false
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect

    Regards::
    AKHIL

  23. i forget to post the code:

    package model;

    import java.util.Date;
    import java.util.Properties;

    import javax.mail.Address;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Provider;
    import javax.mail.Session;
    import javax.mail.Store;
    import javax.mail.URLName;
    import com.sun.mail.pop3.POP3SSLStore;

    public class RecupMail {

    public static boolean ReceiveMessage(String username,String password) {

    boolean result=false;
    //String host = “pop.gmail.com”;
    //String username = “nestinho855@gmail.com”;
    //String password = “NDEYAKENY”;

    //Properties props = new Properties();
    Properties props = new Properties();
    props.put(“mail.pop3.host” , “pop.gmail.com”);
    props.put(“mail.pop3.user” , “username”);
    // Start SSL connection
    props.put(“mail.pop3.socketFactory” , 995 );
    props.put(“mail.pop3.socketFactory.class” , “javax.net.ssl.SSLSocketFactory” );
    props.put(“mail.pop3.port” , 995);

    props.setProperty(” mail.pop3.keepmessagecontent”,”TRUE”);
    props.setProperty(” mail.pop3.rsetbeforequit”,”TRUE”);
    props.setProperty(” mail.pop3.disabletop”,”TRUE”);
    props.setProperty(“mail.pop3.forgettopheaders”,”TRUE”);
    props.setProperty(” mail.pop3.filecache.enable”,”TRUE”);
    props.setProperty(“mail.pop3.starttls.enable”,”TRUE”);

    props.setProperty(“mail.pop3.starttls.required”,”TRUE”);
    props.setProperty(“mail.pop3.cachewriteto”,”TRUE”);
    props.setProperty(“mail.pop3.starttls.required”,”TRUE”);
    props.setProperty(“mail.pop3.disablecapa “,”TRUE”);
    props.setProperty(“mail.pop3.keepmessagecontent”,”TRUE”);
    props.setProperty(“mail.pop3.apop.enablet”,”TRUE”);
    props.put(“mail.pop3.ssl.enable”, “isSsl”);

    //props.setProperty(“mail.pop3.socketFactory.port”, “995”);
    // props.setProperty(“mail.pop3.port”, “995”);
    // props.put(“mail.pop3.host”, “Gmal.com”);
    // props.put(“mail.pop3.auth”, “isSsl”);
    //props.put(“mail.pop3.auth”, isSsl);
    // props.put(“mail.pop3.auth”, isSsl);

    URLName url = new URLName(“pop3″,”gmail.com” ,995,””,username, password);
    System.out.println(username+” et “+password);

    //Session session = Session.getInstance(props, null);
    //hy;

    //********
    //***creation objet session
    Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication(){
    return new PasswordAuthentication(“nestinho855@gmail.com”,”NDEYAKENY”);
    }
    });

    session.setDebug(true);
    //Store store = new POP3SSLStore(session, url);
    System.out.println(“j’y suis”);
    //****fin creation session

    // Opening the Inbox Folder
    // store = session.getStore();
    // store.connect();
    //Folder folder = store.getFolder(“INBOX”);
    //folder.open(Folder.READ_WRITE);
    //

    try{
    Store store = session.getStore(“pop3″);
    store = new POP3SSLStore(session, url);
    store.connect(“pop.gmail.com” , “nestinho855@gmail.com” , “NDEYAKENY”);
    // store = session.getStore();
    // store.connect(” googlemail.l.google.com”,”nestinho855@gmail.com”,”NDEYAKENY”);
    store.connect();
    //Session session = Session.getDefaultInstance(properties, null);

    store = session.getStore(“pop3″);
    // store.connect(server, username, password);

    System.out.println(“connect reusit”);
    Folder folder = store.getDefaultFolder();
    folder = store.getFolder(“INBOX”);
    //Folder folder = store.getFolder(“INBOX”);
    folder.open(Folder.READ_ONLY);

    //folder.open(Folder.READ_WRITE);
    // Getting message totals and messages from a folder
    int totalMessages = folder.getMessageCount();
    System.out.println(“nombre total de message=: “+totalMessages);
    Message[] msgs = folder.getMessages();

    for(int i=0;i<msgs.length;i++)
    {
    // Message m = msgs[i];
    //System.out.println("Retrieving message n° "+i+": subject="+m.getSubject());
    //****
    Address[] from = msgs[i].getFrom();
    Address[] to = msgs[i].getRecipients(Message.RecipientType.TO);
    String subject = msgs[i].getSubject();
    Date d = msgs[i].getSentDate();
    System.out.println("Retrieving message n° "+i+" "+": subject="+" "+subject+"destinataire="+to+" "+"from="+from+" "+"date="+" "+d);
    //***
    }
    store.close();
    result=true;

    }catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s