Sending Emails in Java using GMail ID

Thought of sharing following code with you all. It is a small code snippet that uses SMTP in Java to login into GMail and send email using ones GMail account.

String host = "smtp.gmail.com";
    String from = "username";
    String pass = "password";
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", "true"); // added this line
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    String[] to = {"to@gmail.com"}; // added this line

    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

    InternetAddress[] toAddress = new InternetAddress[to.length];

    // To get the array of addresses
    for( int i=0; i < to.length; i++ ) { // changed from a while loop
        toAddress[i] = new InternetAddress(to[i]);
    }
    System.out.println(Message.RecipientType.TO);

    for( int i=0; i < toAddress.length; i++) { // changed from a while loop
        message.addRecipient(Message.RecipientType.TO, toAddress[i]);
    }
    message.setSubject("sending in a group");
    message.setText("Welcome to JavaMail");
    Transport transport = session.getTransport("smtp");
    transport.connect(host, from, pass);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();

The code is pretty much self explanatory. Add your GMail username and password in line 7 and 8.

props.put("mail.smtp.user", from);  
props.put("mail.smtp.password", pass);  

And also add the recepient email address in to array in line 12.

String[] to = {"to@gmail.com"}; // added this line  


45 Comments

  • manoj 4 August, 2009, 10:53

    hello

  • manoj 4 August, 2009, 10:54

    hay i am patel manoj

    • Sravans 6 October, 2012, 20:46

      Hai hello

  • Sivasubramaniam Arunachalam 30 November, 2009, 6:05

    Can you give us the associated JARs or the complete import statements?

  • suesi Tran 29 December, 2009, 14:58

    Please send the jar file to my mail too: embedzit@gmail.com

  • Hitesh 5 November, 2010, 23:53

    hey thanks for the Code dear.. its Totally workin nd onw thin is that I was lookin for this thisn since a long time but here i got the Perfect code that is Workin so that thanks a lot.. ! Take care Bye Bye

  • Abhi 25 May, 2011, 0:26

    Thanks a lot for the snippet, works great. Was looking something like that for my project, you saved my time.

  • Mohit 4 September, 2011, 19:34

    I’m trying to run this snippet but got the following Exception
    Please help me:-

    javax.servlet.ServletException: javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. u2sm14732770pbq.9

    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:852)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
    org.apache.jsp.test_005fmail.send_jsp._jspService(send_jsp.java:133)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    com.vtr.globarena.URLCheckFilter.doFilter(URLCheckFilter.java:175)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)

  • MuthuKumar 19 October, 2011, 12:53

    how can i run this program using commandprompt?
    how to set paths for jar files?
    pls help.

  • Nagaraj 14 November, 2011, 11:27

    Provide me the jar files used

    • Omprakash 29 March, 2013, 17:02

      Hi Nagaraj,
      Just include mail.jar in your classpath and you will be able to compile and run the program.

      • sudha 12 June, 2013, 10:03

        Just add acitvation.jar and mail.jar
        Surely u will get Proper output

  • dinesh 14 December, 2011, 12:14

    search for mail.jar and activation.jar

  • DURGESH 27 January, 2012, 11:01

    THANKS A LOT !!!!!!!!!!

  • Rizwan 15 February, 2012, 10:50

    NICE JOB, THANK YOU SO MUCH,HELPED A LOT

  • john 8 March, 2012, 4:43

    nice one pal!!!!

  • dharini 18 March, 2012, 11:16

    hey its not working for me. its getting executed but i am not receiving the mail :( any help appreciated :(

  • Deepak 31 March, 2012, 13:22

    Thanks buddy…..superb code

  • Raj 26 May, 2012, 12:25

    Such a Very good Demo…. Refer this Code ….

  • Ketaki Sinkar 4 July, 2012, 18:12

    I m getting this below error:
    Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
    at line
    Session session = Session.getDefaultInstance(props, null);
    Can you please look into this..

    Regards

  • Rohit Ranjan 9 July, 2012, 16:06

    Thanks man … !!! It worked … :-)

  • shwetha marigowda 12 July, 2012, 15:46

    hey the code was really useful..thank you so much

  • sachin kulkarni 20 October, 2012, 14:12

    Hey could u please let me know what packages i have to import

  • suyash 6 November, 2012, 12:47

    Hey Nice post …..Working gmail sender….Cool

  • vinodh 2 December, 2012, 20:05

    my mail sending code is taking 30sec-40sec for one mail.
    how can i reduce this time?
    how can i send mails faster using the java code?

  • shaik akbar ali 4 December, 2012, 10:15

    bahut bahut thanks brother

  • rahul 17 December, 2012, 18:30

    how do i use mail functionality in my existing project and also whatever files like jar i need to run this project.

    plz give a link to download them all

  • Atyab 19 February, 2013, 1:39

    Nice one, It is no doubt an effective code. Thank you sooooooo much !!!! :)

    You taught us something …

  • Atyab 19 February, 2013, 1:49

    YOU ALL CAN DOWNLOAD THE REQUIRED 2 LIBRARIES FROM HERE :

    for mail.jar click on the following link
    http://www.java2s.com/Code/Jar/m/Downloadmailjar.htm

    for javaee.jar
    http://www.java2s.com/Code/Jar/j/Downloadjavaeejar.htm

    After installation right click on your “project folder icon” which is in Package Explorer , then click on “Build Path” , then click on “configure build path” and finally click on “Import External JARs”

  • Subhash 20 February, 2013, 19:46

    Hello Sir,
    I am able to send email from local host but not able to send mail from server on which I host my web site.
    I have used this configuration…Please check..

    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″);

  • karthik 7 March, 2013, 0:11

    i got tis error while trying it

    Error 500: javax.mail.MessagingException: Can’t send command to SMTP host; nested exception is: javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.g: PKIX path building failed: java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl could not build a valid CertPath.; internal cause is: java.security.cert.CertPathValidatorException: The certificate issued by CN=avast! Mail Scanner Root, O=avast! Mail Scanner, OU=generated by avast! antivirus for SSL scanning is not trusted; internal cause is: java.security.cert.CertPathValidatorException: Certificate chaining error

    • dheeraz 9 March, 2013, 9:14

      Error 500: javax.mail.MessagingException: Exception reading response; nested exception is: javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.g: PKIX path building failed: java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl could not build a valid CertPath.; internal cause is: java.security.cert.CertPathValidatorException: The certificate issued by EMAILADDRESS=support@fortinet.com, CN=FortiGate CA, OU=Certificate Authority, O=Fortinet, L=Sunnyvale, ST=California, C=US is not trusted; internal cause is: java.security.cert.CertPathValidatorException: Certificate chaining error

  • karthick 19 March, 2013, 11:18

    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host:
    I am geeting this exception please help me

    smtp.gmail.com, port: 587;
    nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1008)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:197)
    at javax.mail.Service.connect(Service.java:233)
    at javax.mail.Service.connect(Service.java:134)
    at com.SendMail.send(SendMail.java:58)
    at com.SendMail.main(SendMail.java:66)

    • Kiran P. 9 January, 2014, 13:05

      Hi Karthik,

      I am also facing the same error. Will you please help if you have solved that one.? I spent two days over that.Your help will be most appreciated.

  • Girish 25 March, 2013, 13:27

    Lot of errors in Properties put method and showing errors for host, from, to variables.
    Im beginner..
    Anybody pls give some explanation to d code.. pls

    • Omprakash 29 March, 2013, 17:08

      Hi Girish,
      Please import java.util.Properties. Your compilation will only take java.lang. Any class apart from that is being used in the class, then it must be referenced using an import statement.

      You can use Ctrl+O in Eclipse to auto import the class if you have the required jars in your buildpath.

  • Mounesh 17 May, 2013, 14:11

    i am not able to send the mail via gmail,
    The below snippent is my code:

    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Authenticator;
    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 Mail {
     
    	 
    	String d_email = " ", d_password = "   ",
    			d_host = "smtp.gmail.com", d_port = "465", m_to = null,
    			m_subject = "Data integrity Alert from TPA ", m_text = null;
    
    	public Mail( ) {
    
     
    		String s1 = " ";
    
    		SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
    		SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
    
    		Date now = new Date();
    
    		String strDate = sdfDate.format(now);
    		String strTime = sdfTime.format(now);
    
    		String dt = strDate + "   " + strTime;
    
    		m_to = s1;
    		m_text = "  ";
    
    		Properties props = System.getProperties();
    		props.put("mail.smtp.user", d_email);
    		props.put("mail.smtp.host", d_host);
    		props.put("mail.smtp.port", d_port);
    		props.put("mail.smtp.starttls.enable", "true");
    		props.put("mail.smtp.auth", "true");
    		// props.put("mail.smtp.debug", "true");
    		props.put("mail.smtp.socketFactory.port", d_port);
    		props.put("mail.smtp.socketFactory.class",
    				"javax.net.ssl.SSLSocketFactory");
    		props.put("mail.smtp.socketFactory.fallback", "false");
    
    		SecurityManager security = System.getSecurityManager();
    
    		try {
    
    			Authenticator auth = new SMTPAuthenticator();
    			Session session = Session.getInstance(props, auth);
    			// session.setDebug(true);
    
    			MimeMessage msg = new MimeMessage(session);
    			msg.setText(m_text);
    
    			msg.setSubject(m_subject);
    			msg.setFrom(new InternetAddress(d_email));
    			msg.addRecipient(Message.RecipientType.TO,
    					new InternetAddress(m_to));
    			Transport.send(msg);
    		} catch (Exception mex) {
    			mex.printStackTrace();
    		}
    	}
    
    	private class SMTPAuthenticator extends javax.mail.Authenticator {
    		public PasswordAuthentication getPasswordAuthentication() {
    			return new PasswordAuthentication(d_email, d_password);
    		}
    	}
    }
    
  • sheraz 7 July, 2013, 0:20

    Very informative, Thanks for sharing, But I came across another java email component by the name of Aspose.Email for Java. It enables Java applications to read and write MS Outlook MSG files from within a Java application and also support Exchange server as well. I am sure it will be helpful.

  • ayush 16 July, 2013, 21:06

    i tried your code but i am getting the following exception:
    please help!!

    Exception in thread "main" javax.mail.MessagingException: Could not convert socket to TLS;
      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.startTLS(SMTPTransport.java:1907)
    	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)
    	at javax.mail.Service.connect(Service.java:345)
    	at javax.mail.Service.connect(Service.java:226)
    	at ftp.MailMessage.main(MailMessage.java:51)
    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.startTLS(SocketFetcher.java:465)
    	at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1902)
    	... 4 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)
    	... 14 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)
    	... 20 more
    Java Result: 1
    BUILD SUCCESSFUL (total time: 3 seconds)
    
  • Raj Solanki 23 August, 2013, 18:32

    This is really a nice article and i wanted to know that how can i send the email on specific time to the email id of the users which is stored in the database and if i can then how please help as soon as possible as i am on to the deadline of my college project….Please Help me
    Thanks in Advance

  • vani 27 September, 2013, 16:46

    Very nice, whatever the programs you add in your website’s are awesome and works as expected very nice Sir.

  • bala 24 March, 2014, 11:35

    To
    Exception in thread “main” javax.mail.MessagingException: Can’t send command to SMTP host;
    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.sendCommand(SMTPTransport.java:1564)
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1551)
    at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:935)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:426)
    at javax.mail.Service.connect(Service.java:288)
    at javax.mail.Service.connect(Service.java:169)
    at javamail.main(javamail.java:57)
    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:1836)
    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:1337)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154)
    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:966)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1262)
    at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:680)
    at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:85)
    at com.sun.mail.util.TraceOutputStream.write(TraceOutputStream.java:114)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1562)
    … 6 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:1319)
    … 17 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)
    … 23 more
    Java Result: 1

  • bala 24 March, 2014, 11:44

    help me i need to send the mail using java.. how can i send the mail

  • shivangi 5 April, 2014, 10:33

    can u please xplain this code.

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *