Sending E-Mail Using GMail SMTP via Apache Commons Emails

GMail provides a handy and reliable SMTP mail server for your program / script. Following are GMail SMTP configuration settings:

  • SMTP Host Name: smtp.gmail.com
  • SMTP Port: 587
  • TLS Enabled: Yes
  • Username: <your GMail email>
  • Password: <your gmail password>

In Java you can use commons-email to simply send an E-Mail using your GMail account.

First add commons-email jar into your classpath. If you use Maven, simply add following dependency (or newer version if any):

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-email</artifactId>
  <version>1.3.1</version>
</dependency>

Following example assumes your GMail email is johndoe@gmail.com and password abcd1234.

Email email = new SimpleEmail();
email.setSmtpPort(587);
email.setHostName("smtp.gmail.com");
email.setAuthentication("johndoe@gmail.com", "abcd1234");
email.setStartTLSEnabled(true);
email.setFrom("johndoe@gmail.com", "John Doe");
email.setSubject("Hi this is testing email only");
email.setMsg("Hello there testing to send email from GMail");
email.addTo("someone@outhere.com");
email.send();

Note that by default GMail only allows email to be sent from your address (johndoe@gmail.com), you cannot send as somebody else for security reason. You need to perform additional configuration to allow external email to be sent via your GMail account.

Advertisements

One thought on “Sending E-Mail Using GMail SMTP via Apache Commons Emails

  1. Pingback: hMailServer for Outbound Only SMTP Server | Otherwise I'll Forget

Leave a Reply

Please log in using one of these methods to post your comment:

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