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.
Code language: Java (java)
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 = {“[email protected]”}; // 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(); [/code] The code is pretty much self explanatory. Add your GMail username and password in line 7 and 8. [code="java"] props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); [/code] And also add the recepient email address in to array in line 12. [code="java"] String[] to = {"[email protected]"}; // added this line [/code]
Get our Articles via Email. Enter your email address.

You may also like...

46 Comments

  1. manoj says:

    hello

  2. manoj says:

    hay i am patel manoj

    • Sravans says:

      Hai hello

  3. Sivasubramaniam Arunachalam says:

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

  4. suesi Tran says:

    Please send the jar file to my mail too: [email protected]

  5. Hitesh says:

    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

  6. Abhi says:

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

  7. Mohit says:

    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)

  8. MuthuKumar says:

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

  9. Nagaraj says:

    Provide me the jar files used

    • Omprakash says:

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

      • sudha says:

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

  10. dinesh says:

    search for mail.jar and activation.jar

  11. DURGESH says:

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

  12. Rizwan says:

    NICE JOB, THANK YOU SO MUCH,HELPED A LOT

  13. john says:

    nice one pal!!!!

  14. dharini says:

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

  15. Deepak says:

    Thanks buddy…..superb code

  16. Raj says:

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

  17. Ketaki Sinkar says:

    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

  18. Rohit Ranjan says:

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

  19. shwetha marigowda says:

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

  20. sachin kulkarni says:

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

  21. suyash says:

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

  22. vinodh says:

    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?

  23. shaik akbar ali says:

    bahut bahut thanks brother

  24. rahul says:

    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

  25. Atyab says:

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

    You taught us something …

  26. Atyab says:

    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”

  27. Subhash says:

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

  28. karthik says:

    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 says:

      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 [email protected], 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

  29. karthick says:

    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. says:

      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.

  30. Girish says:

    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 says:

      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.

  31. Mounesh says:

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

  32. sheraz says:

    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.

  33. ayush says:

    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)
    

  34. 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

  35. vani says:

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

  36. bala says:

    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

  37. bala says:

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

  38. shivangi says:

    can u please xplain this code.

  39. srikanth says:

    at the time sending mail its taking 60-70 seconds , please revert me if you know

Leave a Reply

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