Send email in Java with gmail SMTP

Send email in Java with gmail SMTP example.

MailUtil.java
package mailtest;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtil {

    private String SMTP_HOST = "smtp.gmail.com";
    private String FROM_ADDRESS = "yourname@gmail.com";
    private String PASSWORD = "yourpassword";
    private String FROM_NAME = "Sameera";

    public boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message) {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", SMTP_HOST);
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "false");
            props.put("mail.smtp.ssl.enable", "true");

            Session session = Session.getInstance(props, new SocialAuth());
            Message msg = new MimeMessage(session);

            InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME);
            msg.setFrom(from);

            InternetAddress[] toAddresses = new InternetAddress[recipients.length];
            for (int i = 0; i < recipients.length; i++) {
                toAddresses[i] = new InternetAddress(recipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, toAddresses);


            InternetAddress[] bccAddresses = new InternetAddress[bccRecipients.length];
            for (int j = 0; j < bccRecipients.length; j++) {
                bccAddresses[j] = new InternetAddress(bccRecipients[j]);
            }
            msg.setRecipients(Message.RecipientType.BCC, bccAddresses);

            msg.setSubject(subject);
            msg.setContent(message, "text/plain");
            Transport.send(msg);
            return true;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
            return false;

        } catch (MessagingException ex) {
            Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    class SocialAuth extends Authenticator {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);

        }
    }
}


Main.java

package mailtest;

public class Main {

    public static void main(String[] args) {
        String[] recipients = new String[]{"youremail@yahoo.com"};
        String[] bccRecipients = new String[]{"youremail@gmail.com"};
        String subject = "Hi this is test Mail";
        String messageBody = "Test Mail from codesstore.blogspot.com";

        new MailUtil().sendMail(recipients, bccRecipients, subject, messageBody);

    }
}
 
Note: mail.jar  is required.

Can add multiple recipients and BCC recipients
String[] recipients = new String[]{"youremail@yahoo.com","youremail2@yahoo.com"};

Instead of msg.setContent(message, "text/plain") you can use msg.setContent(message, "text/html") then you can add html tags to message body.



Note:
Your gmail account  should have 'Access for less secure apps'.
Turn on following,
https://www.google.com/settings/security/lesssecureapps



Note (2022/06/15) :
'Access for less secure apps'  feature is no longer available and you need to create an app password.
Go to 'Account -> security -> Signing in to Google' and enable 2-step verificatiion.
Go to 
'Account -> security -> Signing in to Google -> App passwords' and create a password and use this password in smtp credentials.


93 comments:

  1. Hello...!!! Your Code is very helpful....but i am getting this exception while running it on my machine......
    Can you help me sort this out....

    ReplyDelete
  2. Hi sameera.... How to run this code??

    ReplyDelete
  3. How to solve the javax.mail.SendFailedException: Sending failed; nested exception is: class javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection timed out: connect..
    Now am having this exception

    ReplyDelete
    Replies
    1. This is the code for sending emails using Gmail SMTP settings.You have to use your gmail account details for following variables.

      private String FROM_ADDRESS = "yourname@gmail.com";
      private String PASSWORD = "yourpassword";

      I think you have used localhost as SMTP_HOST.That's why code didn't work.

      Delete
    2. i have used SMTP_HOST = "smtp.gmail.com";, still it is throwing the same error.
      Oct 09, 2013 10:54:43 PM mail.MailUtil sendMail
      SEVERE: null
      javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
      nested exception is:
      java.net.ConnectException: Connection timed out: connect

      Delete
    3. Your port is 25,Port should be 465. try this
      props.put("mail.smtp.port", "465");

      Delete
  4. Hi
    i got this problem
    javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    how to fix this.

    ReplyDelete
    Replies
    1. Check weather your internet connection is working properly, proxy or firewall not blocked gmail.
      Check whether variables and properties are set correctly.

      Delete
  5. great i found it is working.........thanks a lot man.........

    ReplyDelete
  6. Hi Sameera; Thanks for uploading the Email code,
    I need your help in this code..... I got error when i run this code.

    Oct 24, 2012 12:34:53 PM main.MailUtil sendMail
    SEVERE: null
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. gm7sm3389594wib.10

    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at main.MailUtil.sendMail(MainUtil.java:56)
    at main.Main.main(Main.java:17)

    Thanks alot.

    ReplyDelete
  7. Hi while i m using this code i m getting following Error.... please help me to clear this
    ERROR:
    com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. qj6sm3608658pbb.69

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:959)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:583)
    at javax.mail.Transport.send0(Transport.java:169)
    at javax.mail.Transport.send(Transport.java:98)
    at nvnr.MailUtil.sendMail(MailUtil.java:60)
    at nvnr.Main.main(Main.java:19)

    ReplyDelete
    Replies
    1. That code works fine for me.

      Did you set the following property to 'true'
      props.put("mail.smtp.ssl.enable", "true");

      Delete
    2. yes I set the property to "true".

      Delete
  8. im using jsp with tomcat server..where should i add these java files and compile them.i want to send mail through jsp.

    ReplyDelete
    Replies
    1. You can import MailUtil.java to your jsp and add the mail sending code which is in main method to your jsp.
      add mail.jar to your libs.

      You only use JSPs? Don't you use Servlets. It is a bad practice.
      If you use servlets you can import MailUtil.java to your servlet.

      Delete
    2. i pinged smtp.gmail.com the reply was " Ping request could not find host smtp.gmail.com ". Please check the name and try a
      gain.

      Delete
    3. may be your proxy blocked smtp.gmail.com

      Delete
  9. How can i send an attachment with mail??????????

    ReplyDelete
    Replies
    1. 1)Change method and add file array

      public boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message, String files[]) {

      2)
      Remove Line 51 msg.setContent(message, "text/plain"); and add this code

      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setContent(message, "text/plain");
      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);

      for (int k = 0; k < files.length; k++) {
      String filename = files[k];
      MimeBodyPart attachmentBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(filename);
      attachmentBodyPart.setDataHandler(new DataHandler(source));
      attachmentBodyPart.setFileName(filename);
      multipart.addBodyPart(attachmentBodyPart);
      }

      msg.setContent(multipart);

      3) add attachment to Main.java line 10

      String[] files={"C:/Users/home/Pictures/testimage.jpg"};
      new MailUtil().sendMail(recipients, bccRecipients, subject, messageBody,files);

      Delete
    2. This comment has been removed by the author.

      Delete
  10. Getting below error while running above code. Please help
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:

    ReplyDelete
  11. this code work fine with glassfish server.

    ReplyDelete
  12. I use your code and on server i have error Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect
    my props is good:
    m_properties = new Properties();
    m_properties.put("mail.smtp.host", "smtp.gmail.com");
    m_properties.put("mail.smtp.socketFactory.port", "465");
    m_properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    m_properties.put("mail.smtp.auth", "true");
    m_properties.put("mail.smtp.port", "465");
    m_properties.put("mail.debug", "false");
    m_properties.put("mail.smtp.ssl.enable", "true");

    and i couldn't figure out cause of this error..

    ReplyDelete
  13. Hi Sameera,

    I want to use the SMTP service which is running in the server(localhost) instead of a gmail account from the application. Help me..

    Maha

    ReplyDelete
  14. how to get rid of following error:


    javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 465; nested exception is: java.net.ConnectException: Connection refused: connect

    ReplyDelete
    Replies
    1. I think you have used localhost as SMTP_HOST.. use smtp.gmail.com

      Delete
  15. Mar 23, 2013 6:15:18 AM MailUtil sendMail
    SEVERE: null
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command f
    irst. jk1sm1263378pbb.14 - gsmtp

    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at MailUtil.sendMail(Send.java:51)
    at Send.main(Send.java:83)

    ReplyDelete
  16. when i use above your code at that time got this exception how can i solve this exception pls help me thanks a lot

    ReplyDelete
  17. hi please give me a code to upload an image into database with text fields
    please...
    please help sameera..

    thanks in advance

    ReplyDelete
  18. Hi tried running this code i got this exception nested exception is:
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
    nested exception is:

    I dont know how to include/exclude my proxy settings...

    ReplyDelete
  19. This is hard code foe multiple recipients , if i want to send using GUI. then how we can do it?
    thanks . Reply

    ReplyDelete
    Replies
    1. "recipients" is an array. Can't you create an array putting all recipients dynamically.

      Delete
  20. Hi Sameera ,
    I am getting this error i am unable to figure out can you pls help me ?

    Jun 5, 2013 3:10:34 PM mailtest.MailUtil sendMail
    SEVERE: null
    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:1961)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at mailtest.MailUtil.sendMail(MailUtil.java:52)
    at mailtest.Main.main(Main.java:11)
    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:1747)
    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:1209)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:135)
    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:943)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    ... 8 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:1188)
    ... 19 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)
    ... 25 more

    ReplyDelete
  21. Hi Sameera,

    When I run the above code getting below exception.



    com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
    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:367)
    at javax.mail.Service.connect(Service.java:226)
    at javax.mail.Service.connect(Service.java:175)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at com.qwest.mail.DummyTest.sendMail(DummyTest.java:115)
    at com.qwest.mail.TestMail.main(TestMail.java:41)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(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:297)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:229)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    ... 8 more


    Could you please help me in resolving this ?

    ReplyDelete
  22. behen chd 97%laye ho scjp mein aur ye nahi pata ki
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
    error kyu aa rahi hai!!!!
    there is some error in javax jar .

    ReplyDelete
    Replies
    1. I can't understand your language.
      anyway i think you have used port 25, please use port 465 instead

      Delete
  23. This comment has been removed by the author.

    ReplyDelete
  24. Hi
    i got this problem
    MailUtil sendMail
    SEVERE: null
    javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Learn more at
    534-5.7.9 http://support.google.com/accounts/bin/answer.py?answer=185833
    534 5.7.9 {ASPREQUIRED} pm7sm23311582pbb.31 - gsmtp

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:648)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:583)
    at javax.mail.Service.connect(Service.java:297)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at pdp.database.MailUtil.sendMail(MailUtil.java:52)
    at pdp.database.Main.main(Main.java:11)

    how to fix this.

    ReplyDelete
    Replies
    1. i also got the same exception then fixed it using the following post http://stackoverflow.com/questions/8620935/sending-email-through-java-in-gmail-account-having-two-way-authentication

      Delete
  25. i tried your code. i need to use it to send a mail from my project application. but it shows the following exception.

    Jul 17, 2013 4:45:49 PM ftp.MailUtil sendMail
    SEVERE: null
    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:367)
    at javax.mail.Service.connect(Service.java:226)
    at javax.mail.Service.connect(Service.java:175)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at ftp.MailUtil.sendMail(MailUtil.java:60)
    at ftp.Main.main(Main.java:19)
    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 sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
    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:229)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    ... 8 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:385)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
    ... 19 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:196)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    ... 25 more

    BUILD SUCCESSFUL (total time: 2 seconds)

    Waiting in anticipation..
    Please help me out!

    ReplyDelete
  26. i am getting error like..


    SEVERE: null
    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:1934)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at MailUtil.sendMail(MailUtil.java:50)
    at Main.main(Main.java:9)
    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(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:507)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    ... 8 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(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.Validator.validate(Unknown Source)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    ... 19 more
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 25 more






    and my firewall is also off please help me as soon as possible....thank in advance :)

    ReplyDelete
  27. Your code is working awesome..can you send me the code for how to attach the zip folder using gmail.

    ReplyDelete
    Replies
    1. http://codesstore.blogspot.com/2011/10/send-email-in-java-with-gmail.html?showComment=1355247525911#c3490848445361094482

      Delete
  28. ERROR [STDERR] javax.mail.MessagingException: Could not connect to SMTP host: mail.technosoftcorp.com, port: 25;
    nested exception is:
    java.net.ConnectException: Connection refused: connect
    12:59:28,765 ERROR [STDERR] at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
    12:59:28,765 ERROR [STDERR] at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    12:59:28,765 ERROR [STDERR] at javax.mail.Service.connect(Service.java:275)
    12:59:28,765 ERROR [STDERR] at javax.mail.Service.connect(Service.java:156)
    12:59:28,765 ERROR [STDERR] at javax.mail.Service.connect(Service.java:105)
    12:59:28,765 ERROR [STDERR] at javax.mail.Transport.send0(Transport.java:168)
    12:59:28,765 ERROR [STDERR] at javax.mail.Transport.send(Transport.java:98)
    12:59:28,765 ERROR [STDERR] at com.action.LoginAction.SendHTMLEmail(LoginAction.java:213)
    12:59:28,765 ERROR [STDERR] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    12:59:28,765 ERROR [STDERR] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    12:59:28,765 ERROR [STDERR] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    12:59:28,765 ERROR [STDERR] at java.lang.reflect.Method.invoke(Unknown Source)
    12:59:28,765 ERROR [STDERR] at org.apache.el.parser.AstValue.invoke(AstValue.java:170)
    12:59:28,765 ERROR [STDERR] at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    12:59:28,765 ERROR [STDERR] at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
    12:59:28,781 ERROR [STDERR] at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    12:59:28,781 ERROR

    ReplyDelete

  29. while i running that code shows an exception like this


    com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. nj9sm533450pbc.13 - gsmtp

    ReplyDelete
  30. what exactly i developed my code in ibm is same look like this
    ok good and very useful....

    can you please help me with sending mail one after the other.
    ex:in string TO[] i entered 4 mails .then i have to send one after the other not at a time once.can u help me on this.

    ReplyDelete
  31. thanks...... u r coding is working... but one more thing... how to attach a file.

    ReplyDelete
    Replies
    1. I already explained it in this comment,
      http://codesstore.blogspot.com/2011/10/send-email-in-java-with-gmail.html?showComment=1355247525911#c3490848445361094482

      Delete
    2. No.. My question is how to attached the file with Email.. like doc. pdf, zip file

      Delete
    3. Yes, you can attach any file type using that method.

      Delete
  32. String to = "xxxxxxx@gmail.com";//change accordingly
    String from = "xxxxxxxx@gmail.com";//change accordingly
    String host = "smtp.gmail.com";//or IP address

    //Get the session object
    Properties properties = System.getProperties();
    properties.put("mail.debug","true");
    properties.setProperty("mail.smtp.host", host);
    //properties.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(properties, null);

    //compose the message
    try{
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
    message.setSubject("Ping");
    message.setText("Hello, this is example of sending email ");

    // Send message
    Transport.send(message);
    System.out.println("message sent successfully....");

    }catch (MessagingException mex) {mex.printStackTrace();}

    this is my code am getting these error please give the suggestion

    DEBUG: not loading system providers in /lib
    DEBUG: not loading optional custom providers file: /META-INF/javamail.providers
    DEBUG: successfully loaded default providers

    DEBUG: Tables of loaded providers
    DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]}
    DEBUG: Providers Listed By Protocol: {imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
    DEBUG: not loading optional address map file: /META-INF/javamail.address.map

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

    DEBUG: SMTPTransport trying to connect to host "smtp.gmail.com", port 25

    DEBUG SMTP RCVD: 220 mx.google.com ESMTP gw10sm34899779pbd.13 - gsmtp

    DEBUG: SMTPTransport connected to host "smtp.gmail.com", port: 25

    DEBUG SMTP SENT: EHLO LAP1
    DEBUG SMTP RCVD: 250-mx.google.com at your service, [202.83.31.39]
    250-SIZE 35882577
    250-8BITMIME
    250-STARTTLS
    250-ENHANCEDSTATUSCODES
    250 CHUNKING

    DEBUG SMTP SENT: MAIL FROM:
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. gw10sm34899779pbd.13 - gsmtp
    DEBUG SMTP RCVD: 530 5.7.0 Must issue a STARTTLS command first. gw10sm34899779pbd.13 - gsmtp

    DEBUG SMTP SENT: QUIT

    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at Mymail.main(Mymail.java:40)

    ReplyDelete
  33. Hi Sameera,
    This Is Ravindar,
    iam configuring jndi mail session in application server.
    iam using jndi mailsession in my web application using servlets.....
    after giving request from browser iam getting error on SystemLogs
    like
    Messaging Excxeption------------:com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. om6sm59970948pbc.43 - gsmtp



    can u give me the solution

    ReplyDelete
  34. hi...
    I tried running this example but it gives exception like
    description: The server encountered an internal error() that prevented it from fulfilling the request.
    please... can you help me to solve it? I need this code.

    ReplyDelete
  35. i got this below exception please help me


    Exception in thread "main" java.lang.NoClassDefFoundError: Main (wrong name: mailtest/Main)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:472)

    ReplyDelete
  36. Hello Sameera,
    I followed your post and it helped to send emails to 102 users every 12 hours using scheduler.
    But for enhancement, I want to send emails to email thread. Please help me in this case.

    Thanks,
    Abhijit

    ReplyDelete
  37. It worked! It worked! Thanks, Sameera, you have no idea how much I struggled with this, you just saved my butt. Thanks again, buddy.

    ReplyDelete
  38. when I run my code the following error appears: javax.mai.messagingException: could not connect to SMTP host: smtp.gmail.com, port: 465;

    ReplyDelete
  39. i want to read the email from gmail account.. and want to add some of them in to data base on the basis of some filter.

    ReplyDelete
  40. This comment has been removed by the author.

    ReplyDelete
  41. This comment has been removed by the author.

    ReplyDelete
  42. Nov 4, 2015 4:15:04 PM mailtest.MailUtil sendMail
    SEVERE: null
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. tj2sm1342680pab.4 - gsmtp

    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at mailtest.MailUtil.sendMail(MailUtil.java:57)
    at mailtest.Main.main(Main.java:16)
    BUILD SUCCESSFUL (total time: 3 seconds)

    ReplyDelete
  43. Hi Guys

    Google may block sign-in attempts from some apps or devices that do not use
    Note:-Please Login your gmail account first
    so,to unblock open browser and search this->"allow any devices for gmail client"
    After click on search
    Click on 1st listed link
    Allowing less secure apps to access your account page will open
    click on 1.Go to the "Less secure apps" section in My Account. and this take you
    "Less secure apps" page overhere you have to change setting from trun off to trun on
    then it will allow you to send mail
    hope this will work for you























    ReplyDelete
  44. what about this Probelm Host is unresolved: smtp.gmail.com.
    working with the emulator..when i on wifi its work but when i switched to 3g its show that messages Host is unresolved: smtp.gmail.com

    ReplyDelete
  45. Thank you my friend, very good.

    ReplyDelete
  46. thanks ,you code works very weel

    ReplyDelete
  47. HI sameer when i run your code ..the follwoing error is coming pls help me how to solve..

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1545)

    ReplyDelete
  48. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Best Devops Training in pune
    Microsoft azure training in Bangalore

    ReplyDelete

  49. It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.

    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training
    Selenium training in bangalore

    ReplyDelete
  50. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage
    contribution from other ones on this subject while our own child is truly discovering a great deal.
    Have fun with the remaining portion of the year.
    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  51. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.

    python training in rajajinagar
    Python training in bangalore
    Python training in usa

    ReplyDelete
  52. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.
    python training in rajajinagar
    Python training in bangalore
    Python Online training in usa

    ReplyDelete
  53. Thanks For Sharing The Information The information shared Is Very Valuable Please Keep Updating Us Time just went On reading The article Python Online Training Aws Online Training Hadoop Online Training Data Science Online Training

    ReplyDelete
  54. Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.
    Java Training in Chennai | J2EE Training in Chennai | Advanced Java Training in Chennai | Core Java Training in Chennai | Java Training institute in Chennai

    ReplyDelete
  55. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.Informatica Training in Bangalore

    ReplyDelete
  56. ThankUuuu VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY VERY MUchhhhh BHaaaIiiiiiiiii ……………

    ReplyDelete
  57. Superb.. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing post.
    AWS training in Chennai

    AWS Online Training in Chennai

    AWS training in Bangalore

    AWS training in Hyderabad

    AWS training in Coimbatore

    AWS training

    ReplyDelete
  58. Great post! I am actually getting ready to across this information, It’s very helpful for this blog. Also great with all of the valuable information you have Keep up the good work you are doing well.
    hardware and networking training in chennai

    hardware and networking training in tambaram

    xamarin training in chennai

    xamarin training in tambaram

    ios training in chennai

    ios training in tambaram

    iot training in chennai

    iot training in tambaram

    ReplyDelete
  59. This is an awesome motivating article. I am practically satisfied with your great work. You put truly extremely supportive data. Keep it up. Continue blogging. Hoping to perusing your next post
    Java Training in Chennai

    Java Training in Velachery

    Java Training inTambaram

    Java Training in Porur

    Java Training in Omr

    Java Training in Annanagar

    ReplyDelete
  60. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete