How to Send Email in Java Using Apache Commons

Apache commons has an email library built on top of Java Mail API. This simplifies the process of sending emails from Java programs. Apache commons email API has classes for sending HTML emails, emails with attachments or even emails with embedded images. For this article, Apache commons email version 1.4 and Java Mail version 1.5.6 is used.

In order to run these examples you need to have Java Mail API library and Apache commons email library.

The following examples use the SMTP email server provided by Google for Gmail. However you can use any other SMTP email server. Don’t forget to change the username and password in the following examples. When using Gmail, you may get the following error,

org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465

To solve the above issue you need to turn on Access for less secure apps from this Google link. This requirement is specific to Gmail accounts.

Following are the configuration attributes for various email providers that you can use in the Java program using Apache commons email library. All the accounts below use the SMTP port of 465 and are SSL enabled.

Email Provider Host name Comments
Gmail smtp.gmail.com Enable less secure access as mentioned above.
Yahoo Mail smtp.mail.yahoo.com From account security tab of your yahoo account, enable allow apps that use less secure sign in.
Sendgrid smtp.sendgrid.net Create an API key in Sendgrid. Use "apikey" as user name the actual API key as the password.
Mailgun smtp.mailgun.org Default SMTP user name and password are available from the default domain page in Mailgun panel. If you are using free account, you can only send to authorized recipients.

 

Sending Simple Text Email in Java Using Apache Commons

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;

// Java program to send simple email using apache commons email
// Uses the Gmail SMTP servers
public class SimpleEmailSender {
    private static final String HOST = "smtp.gmail.com";
    private static final int PORT = 465;
    private static final boolean SSL_FLAG = true; 

    public static void main(String[] args) {
        SimpleEmailSender sender = new SimpleEmailSender();
        sender.sendSimpleEmail();
    }

    private void sendSimpleEmail() {
        
        String userName = "username@gmail.com";
        String password = "password";
        
        String fromAddress="username@gmail.com";
        String toAddress =  "quickprogrammer@gmail.com";
        String subject = "Test Mail";
        String message = "Hello from Apache Mail";
        
        try {
            Email email = new SimpleEmail();
            email.setHostName(HOST);
            email.setSmtpPort(PORT);
            email.setAuthenticator(new DefaultAuthenticator(userName, password));
            email.setSSLOnConnect(SSL_FLAG);
            email.setFrom(fromAddress);
            email.setSubject(subject);
            email.setMsg(message);
            email.addTo(toAddress);
            email.send();
        }catch(Exception ex){
            System.out.println("Unable to send email");
            System.out.println(ex);
        }
    }
}

To compile and run the above programs, ensure that the Apache commons email library jar commons-email-1.4.jar and Java Mail library jar javax.mail.jar is in the same folder where Java source files are stored. Then use the following commands,

To compile in linux/mac,

javac -cp "javax.mail.jar:commons-email-1.4.jar:." SimpleEmailSender.java

To compile in Windows,

javac -cp "javax.mail.jar;commons-email-1.4.jar;." SimpleEmailSender.java

To run in linux/mac,

java -cp "javax.mail.jar:commons-email-1.4.jar:." SimpleEmailSender

To run in Windows,

java -cp "javax.mail.jar;commons-email-1.4.jar;." SimpleEmailSender

If you are using Gradle build system, you can use the following build.gradle for running Java programs using Apache commons email library,

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'org.apache.commons:commons-email:1.4'
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply