Simple mail sending in Java via Gmail/SMTP

If you happen to have Gmail account, and you wish to use it to send mail for any reason to any recipient, that can be done quite easilly.

Adding dependency to commons-email

I suggest using Maven or Gradle to deal with required dependency to commons-email artifact (I’m using Maven for demo) in order to reduce complexity of finding correct jar(s).

In case of Maven, we can add the following dependency to our pom.xml:

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

Client code for commons-email API

Once we’re done with dependency config, we can now use our Apache commons API to simplify mail sending. Let’s start with a code snipet to prove how easy that can be:

package rs.dodalovic.send_mail;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import javax.mail.util.ByteArrayDataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ApacheCommonsEmailSenderMain {

    public static final String HOST_NAME = "smtp.gmail.com";
    public static final int PORT = 465;
    public static final String TEXT_PLAIN = "text/plain";

    public static void main(String[] args) throws IOException, EmailException {

        final String userName = args[0];
        final String password = args[1];
        final String recipientEmailAddress = args[2];
        final String attachmentLocation = args[3];

        HtmlEmail email = new HtmlEmail();
        email.setHostName(HOST_NAME);
        email.setSmtpPort(PORT);
        email.setSSLOnConnect(true);

        email.setAuthentication(userName, password);

        email.setSubject("Some subject");
        email.setFrom(userName, "Firstname Lastname", String.valueOf(StandardCharsets.UTF_8));
        email.addTo(recipientEmailAddress);
        email.setHtmlMsg("
<h3>Message body</h3>
");

        ByteArrayDataSource dataSource = new ByteArrayDataSource(new FileInputStream(attachmentLocation), TEXT_PLAIN);
        email.attach(dataSource, "attachment", "attachment");
        email.send();
    }

}

Our simple application asks for 4 command line parameters:

  1. args[0] – your Gmail username
  2. args[1] – your Gmail password
  3. args[2] – recipient’s email address
  4. args[3] – full path to attachment in local file system

 You could execute application from your favourite IDE by configuring launch configuration, or you can execute main class from command line, such as:

java rs.dodalovic.send_mail.ApacheCommonsEmailSenderMain YOUR_USERNAME@gmail.com YOUR_GMAIL_PASSWORD RECIPIENT_EMAIL_ADDRESS FULL_PATH_TO_ATTACHMENT_FILE

With real values, it might look something like:

java rs.dodalovic.send_mail.ApacheCommonsEmailSenderMain john_doe@gmail.com 123456 foo_bar_baz@server.com /home/john/Desktop/my_attachment.txt

We’re using HtmlEmail API to execute mail sending, which is quite self-explanatory, and for any further interest – you could take a look at API doc.

After executing program, email recipient will receive something similar to:

Selection_002

Key takeaways

Apache commons-email library greatly simplifies e-mail sending by hiding complex Java Mail API. Library itself has small footprint which is additional reason to use.

Source code

Stay tuned and please – don’t forget to subscribe in case you’re eager to find out what’s coming next in upcoming posts.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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