Java Commons Email Tutorial with Examples
1. Introduction
Commons Email is a Java library of Apache involving Email. In fact, in order to work with Java Email, you can use JavaMail API integrated in JDK6. Commons Email only helps you to work with JavaMail API more easily, it can not be a substitute for JavaMail API.
Similarly, Commons IO is no substitute for JavaIO but includes a lot of classes and methods in order to work with Java IO more easily as well as to save code time for you.
2. Library
Maven:
** pom.xml **
<!-- http://mvnrepository.com/artifact/org.apache.commons/commons-email -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.3.2</version>
</dependency>
See Also:
3. Note for Gmail
No ADS
If you want to send email from a Java application that uses Gmail, you need to allow: less secure apps:
On your browser, sign in to your Gmail, and acccess the following link:
You will receive a Google Alert:Some apps and devices use less secure sign-in technology, which makes your account more vulnerable. You can turn off access for these apps, which we recommend, or turn on access if you want to use them despite the risks.
4. Example of sending a simple email
No ADS
First of all, an example to send a simple Email with a Commons-Email
Constants.java
package org.o7planning.tutorial.commonsemail;
public class Constants {
public static final String MY_EMAIL = "yourEmail@gmail.com";
public static final String MY_PASSWORD ="your password";
public static final String FRIEND_EMAIL = "friendEmail@gmail.com";
}
SimpleTextEmail.java
package org.o7planning.tutorial.commonsemail;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
public class SimpleTextEmail {
public static void main(String[] args) {
try {
Email email = new SimpleEmail();
// Configuration
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(Constants.MY_EMAIL,
Constants.MY_PASSWORD));
// Required for gmail
email.setSSLOnConnect(true);
// Sender
email.setFrom(Constants.MY_EMAIL);
// Email title
email.setSubject("Test Email");
// Email message.
email.setMsg("This is a test mail ... :-)");
// Receiver
email.addTo(Constants.FRIEND_EMAIL);
email.send();
System.out.println("Sent!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Running the example:
5. Send email with attachments
No ADS
For example, sending email with a file attached on the hard disk.
EmailWithAttachment.java
package org.o7planning.tutorial.commonsemail;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;
public class EmailWithAttachment {
public static void main(String[] args) {
try {
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("C:/mypictures/map-vietnam.png");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Vietnam Map");
attachment.setName("Map");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
// Configuration
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setSSLOnConnect(true);
email.setAuthenticator(new DefaultAuthenticator(Constants.MY_EMAIL,
Constants.MY_PASSWORD));
email.setFrom(Constants.MY_EMAIL, "TRAN");
email.addTo(Constants.FRIEND_EMAIL, "Hong");
email.setSubject("The Map");
email.setMsg("Here is the map you wanted");
// Add the attachment
email.attach(attachment);
// Send the email
email.send();
System.out.println("Sent!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Results:
Another example is sending an email with attachments from a link.
EmailWithAttachment2.java
package org.o7planning.tutorial.commonsemail;
import java.net.URL;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;
public class EmailWithAttachment2 {
public static void main(String[] args) {
try {
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setURL(new URL(
"http://www.apache.org/images/asf_logo_wide.gif"));
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Apache logo");
attachment.setName("Apache logo");
// Create the email message
MultiPartEmail email = new MultiPartEmail();
// Configuration
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setSSLOnConnect(true);
email.setAuthenticator(new DefaultAuthenticator(
Constants.MY_EMAIL, Constants.MY_PASSWORD));
email.setFrom(Constants.MY_EMAIL, "TRAN");
email.addTo(Constants.FRIEND_EMAIL, "Hong");
email.setSubject("The logo");
email.setMsg("Here is Apache's logo");
// Add the attachment
email.attach(attachment);
// Send the email
email.send();
System.out.println("Sent!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Running the example:
6. Send Email in HTML format
SendHtmlEmail.java
package org.o7planning.tutorial.commonsemail;
import java.net.URL;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.HtmlEmail;
public class SendHtmlEmail {
public static void main(String[] args) {
try {
// Create the email message
HtmlEmail email = new HtmlEmail();
// Configuration
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(
Constants.MY_EMAIL,Constants.MY_PASSWORD));
email.setSSLOnConnect(true);
email.setFrom(Constants.MY_EMAIL, "TRAN");
// Receiver
email.addTo(Constants.FRIEND_EMAIL);
// Title
email.setSubject("Test Sending HTML formatted email");
// Embed the image and get the content id
URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid = email.embed(url, "Apache logo");
// Set the html message
email.setHtmlMsg("<html><h2>The apache logo</h2> <img src=\"cid:"
+ cid + "\"></html>");
// Set the alternative message
email.setTextMsg("Your email client does not support HTML messages");
// Send email
email.send();
System.out.println("Sent!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
7. Send an Email in HTML format, embed photos
No ADS
SendHtmlEmbedImageEmail.java
package org.o7planning.tutorial.commonsemail;
import java.net.URL;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.ImageHtmlEmail;
import org.apache.commons.mail.resolver.DataSourceUrlResolver;
public class SendHtmlEmbedImageEmail {
public static void main(String[] args) {
try {
// Load your HTML email template
// Here, Img has relative location (**)
String htmlEmailTemplate = "<h2>Hello!</h2>"
+"This is Apache Logo <br/>"
+"<img src='proper/commons-email/images/commons-logo.png'/>";
// Create the email message
ImageHtmlEmail email = new ImageHtmlEmail();
// Configuration
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(
Constants.MY_EMAIL, Constants.MY_PASSWORD));
email.setSSLOnConnect(true);
email.setFrom(Constants.MY_EMAIL, "TRAN");
email.addTo(Constants.FRIEND_EMAIL);
email.setSubject("Sending HTML formatted email with embedded images");
// Define you base URL to resolve relative resource locations
// (Example - Img you see above ** )
URL url = new URL("http://commons.apache.org");
email.setDataSourceResolver(new DataSourceUrlResolver(url) );
// Set the html message
email.setHtmlMsg(htmlEmailTemplate);
// Set the alternative message
email.setTextMsg("Your email client does not support HTML messages");
// Send the email
email.send();
System.out.println("Sent!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
No ADS
Java Basic
- Data Types in java
- Java PhantomReference Tutorial with Examples
- JDK Javadoc in CHM format
- Java Stream Tutorial with Examples
- Java Predicate Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- Arrays in Java
- JDBC Driver Libraries for different types of database in Java
- Abstract class and Interface in Java
- Java Commons Email Tutorial with Examples
- Install Eclipse
- Bitwise Operations
- Install Eclipse on Ubuntu
- Configuring Eclipse to use the JDK instead of JRE
- Java Commons Logging Tutorial with Examples
- Java Enums Tutorial with Examples
- Loops in Java
- Java Regular Expressions Tutorial with Examples
- Install Java on Ubuntu
- Quick Learning Java for beginners
- Install Java on Windows
- Comparing and Sorting in Java
- Inheritance and polymorphism in Java
- Java Consumer Tutorial with Examples
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- if else statement in java
- Switch Statement in Java
- Java Supplier Tutorial with Examples
- Java Programming for team using Eclipse and SVN
- Java JDBC Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- What is needed to get started with Java?
- Java Aspect Oriented Programming with AspectJ (AOP)
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java Compression and Decompression Tutorial with Examples
- Java Reflection Tutorial with Examples
- Install OpenJDK on Ubuntu
- Java String.format() and printf() methods
- History of Java and the difference between Oracle JDK and OpenJDK
- Introduction to the Raspberry Pi
- Java Socket Programming Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java WeakReference Tutorial with Examples
- Java Commons IO Tutorial with Examples
- History of bits and bytes in computer science
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java SoftReference Tutorial with Examples
- Syntax and new features in Java 8
- Java Annotations Tutorial with Examples
- Java Function Tutorial with Examples
- Access modifiers in Java
- Java BiFunction Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Functional Interface Tutorial with Examples
- Java BiPredicate Tutorial with Examples
Show More
- Java Servlet/Jsp Tutorials
- Java Collections Framework Tutorials
- Java API for HTML & XML
- Java IO Tutorials
- Java Date Time Tutorials
- Spring Boot Tutorials
- Maven Tutorials
- Gradle Tutorials
- Java Web Services Tutorials
- Java SWT Tutorials
- JavaFX Tutorials
- Java Oracle ADF Tutorials
- Struts2 Framework Tutorials
- Spring Cloud Tutorials