JavaMail API – Sending email via Gmail SMTP example

Here are two examples to show you how to use JavaMail API method to send an email via Gmail SMTP server, using both TLS and SSL connection.

To run this example, you need two dependency libraries – javaee.jar and mail.jar, both are bundle in JavaEE SDK.

Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for TLS/STARTTLS: 587
Port for SSL: 465

GMail SMTP detail here – http://mail.google.com/support/bin/answer.py?hl=en&answer=13287

1. JavaMail – GMail via TLS

Send an Email via Gmail SMTP server using TLS connection.

Example updated on 19/03/2012
Thanks inputs from Sumeet Kumar Yadav and vihor. The below example is updated to get rid of the previous “javax.mail.AuthenticationFailedException” error. It working perfect now.
package com.mkyong.common;
 
import java.util.Properties;
 
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 SendMailTLS {
 
	public static void main(String[] args) {
 
		final String username = "[email protected]";
		final String password = "password";
 
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");
 
		Session session = Session.getInstance(props,
		  new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		  });
 
		try {
 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("[email protected]"));
			message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse("[email protected]"));
			message.setSubject("Testing Subject");
			message.setText("Dear Mail Crawler,"
				+ "\n\n No spam to my email, please!");
 
			Transport.send(message);
 
			System.out.println("Done");
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}

2. JavaMail – GMail via SSL

Send an Email via Gmail SMTP server using SSL connection.

package com.mkyong.common;
 
import java.util.Properties;
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 SendMailSSL {
	public static void main(String[] args) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
 
		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("username","password");
				}
			});
 
		try {
 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("[email protected]"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("[email protected]"));
			message.setSubject("Testing Subject");
			message.setText("Dear Mail Crawler," +
					"\n\n No spam to my email, please!");
 
			Transport.send(message);
 
			System.out.println("Done");
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}
java.net.UnknownHostException: smtp.gmail.com
Some hit the UnknownHostException: smtp.gmail.com, try ping smtp.gmail.com and make sure you got a response (able to access). Often times, your connection may block by your firewall or proxy behind.
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Dibyendu

    Hello,

    Very nicely explained but I need few inputs how to set proxy properties to break through the firewall. I am getting java.net.UnknownHostException: smtp.gmail.com error due to proxy enabled.

    Regards,
    Dibyendu

  • Rajkumar

    hi facing issues while sending ™ in email content using Email class in java.can you please help me in this

  • rbp

    hello
    I have an error, I am sending several different senders mail the problem is that when sending a mail to the sender that your email is wrong or there is entered
    short, non-continuous flow sending, how I can fix this? thanks

    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.1.1 .

  • anony

    thanks buddy!

  • Pingback: Javamail fails but with no exceptions or debug error | Technology & Programming Answers()

  • Amit Ranjan

    Great solution. I had also watch one solution at Youtube.com which works fine. I have learned to mail using java with following youtube video
    http://www.youtube.com/watch?v=ONa3TFdTS88

  • White Roses

    Your SMTP TLS code does not work. I used the same credentials for SMTP SSL and that works:

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at SMTP_TLS.main(SMTP_TLS.java:48)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    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:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at SMTP_TLS.main(SMTP_TLS.java:43)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:299)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    … 7 more

  • marcel

    How can I send Html text with this code?
    Thanks!!

  • Pingback: ConfiguraĆ§Ć£o do SendMail no RedHat | Atitude Reflexiva()

  • http://www.messeng.dsmynas.com RPM

    Thanks a lot……….
    wow I’ve been looking for such a code since 2 weeks!
    Great job mkyong, you are the best…

  • Siddarth

    Great one!!! Works fine.
    But, Here We’ve hard-coded the plain password. So, I want to know how to use encrypted password in the program.

    Could you please tell me?

  • Andrei

    Very nice and perfectly working code! Thanks!