This is the seventh article in a series. For the first few, please click on the link
Good News for programmers – An introduction to Apache Commons
Good news for Programmers – Apache Commons Lang
Programmer’s Gospel – Apache Commons IO
Good news for programmers – Apache Commons Codec
Programmer’s Gospel – Apache Commons Compress
Programmer’s Gospel – Apache Commons Exec
Apache Commons Email is a utility library for sending E-mail in Java. It provides several apis for sending E-mail. It’s built on top of the Java Mail API, mostly to simplify it.
Commons-email is currently in version 1.5 and requires Java6 as a minimum.
Maven coordinates are as follows:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
Copy the code
At the heart of Commons-Email is the Email class, which is an abstract class that provides the core functionality for sending messages. There are several specific implementation classes as follows
SimpleEmail: Send simple messages, or plain text messages
MultiPartEmail: Send mail with attachments
HtmlEmail: sends hypertext messages
ImageHtmlEmail: Sends a hypertext message with mixed images and pictures
Below is the class diagram for Email
You can see a lot of additional information from the class diagram:
HtmlEmail inherits from MultiPartEmail, meaning it also supports attachments.
ImageHtmlEmail inherits HtmlEmail, meaning it also supports attachments and hypertext.
Here’s a brief introduction to how to use it.
01. Email Settings
If you want to send emails through the program, you first need to have an email as the sender, and enable POP3/SMTP service, and obtain the authorization code of the corresponding email. Different email boxes are different in the opening mode and location. The following takes email 163 and QQ as an example.
1. 163
Enter the email home page, click Settings, select POP3/SMTP/IMAP from the drop-down list, click to enter the “POP3/SMTP/IMAP” part, click [Open] after “POP3/SMTP Service”, the page pops up, use the bound mobile phone to scan the code to send short messages, after sending, you can get the authorization code.
2. QQ mailbox
Enter email home page, click Settings, switch to the account TAB, slide the page into “POP3 / IMAP/SMTP/Exchange/CardDAV/CalDAV services” section, click on the “POP3 / SMTP service” after [open], remind using QQ binding mobile phone number will pop up page send text messages, After sending, click “I have sent”, you can get the authorization code.
02. Simple emails
Simple mail is plain text mail with a simple format. Let’s look at an example using the Java API and commons-email API
Java API example:
// Use the Java Mail API
Properties prop = new Properties();
prop.setProperty("mail.host"."smtp.qq.com");
prop.setProperty("mail.transport.protocol"."smtp");
prop.setProperty("mail.smtp.auth"."true");
/ / create the session
Session session = Session.getInstance(prop);
// Set the debug mode of the Session to true to view the running status of the Email sent by the program
// session.setDebug(true);
Transport ts = session.getTransport();
// Take the QQ mailbox as an example. You need to enable the POP3/SMTP service and generate an authorization code for connect
ts.connect("[email protected]"."xxxxxxxxx");
// Create a mail object
MimeMessage message = new MimeMessage(session);
message.setFrom("[email protected]");
message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.setSubject("Javamail Simple Text Mail");
message.setContent("This is a simple email from Javamail."."text/html; charset=UTF-8");
/ / send
ts.sendMessage(message, message.getAllRecipients());
ts.close();
Copy the code
Commons Email example:
// Commons Email example
Email email = new SimpleEmail();
// If the SMTP server is not set, the value of the system variable mail.smtp. Host is queried by default. If not, an exception is thrown
// org.apache.commons.mail.EmailException: Cannot find valid hostname for mail session
email.setHostName("smtp.qq.com");
email.setSmtpPort(465);
// javax.mail.AuthenticationFailedException: 535 Login fail. Authorization code is expired
email.setAuthenticator(new DefaultAuthenticator("[email protected]"."xxxxxxxxx"));
email.setSSLOnConnect(true);
email.setFrom("[email protected]");
email.setSubject("TestMail");
email.setMsg(This is the third test mail... : -)");
email.addTo("[email protected]");
email.send();
Copy the code
As you can see from the example above, the Commons-email API looks a little simpler and cleaner. But because plain text is so simple, there’s not much difference in the amount of code.
03. Complex emails
Complex Email formats, images, attachments, etc. Here’s an example using the Java API and commons-email API
Java API example:
// Use the Java Mail API
Properties prop = new Properties();
prop.setProperty("mail.host"."smtp.qq.com");
prop.setProperty("mail.transport.protocol"."smtp");
prop.setProperty("mail.smtp.auth"."true");
/ / create the session
Session session = Session.getInstance(prop);
Transport ts = session.getTransport();
ts.connect("smtp.qq.com"."[email protected]"."xxxxxxxx");
MimeMessage message = new MimeMessage(session);
// Set basic information
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.setSubject("Javamail sends more comprehensive emails with attachments and pictures and bodies.");
/ / content
MimeBodyPart text = new MimeBodyPart();
text.setContent("Simple portrait:
"."text/html; charset=UTF-8");
/ / picture
MimeBodyPart image = new MimeBodyPart();
image.setDataHandler(new DataHandler(new FileDataSource("D:\\commons mail\\images\\5.jpg")));
image.setContentID("portrait.jpg");
/ / the attachment 1
MimeBodyPart attachment = new MimeBodyPart();
DataHandler handler = new DataHandler(new FileDataSource("D:\\commons mail\\files\\test.docx"));
attachment.setDataHandler(handler);
attachment.setFileName(handler.getName());
2 / / accessories
MimeBodyPart attachment2 = new MimeBodyPart();
DataHandler handler2 = new DataHandler(new FileDataSource("D:\\commons mail\\files\\test2.txt"));
attachment2.setDataHandler(handler2);
attachment2.setFileName(MimeUtility.encodeText(handler2.getName()));
/ / build
MimeMultipart part = new MimeMultipart();
part.addBodyPart(text);
part.addBodyPart(image);
part.setSubType("related");
MimeMultipart part2 = new MimeMultipart();
part2.addBodyPart(attachment);
part2.addBodyPart(attachment2);
MimeBodyPart content = new MimeBodyPart();
content.setContent(part);
part2.addBodyPart(content);
part2.setSubType("mixed");
message.setContent(part2);
message.saveChanges();
/ / send
ts.sendMessage(message, message.getAllRecipients());
ts.close();
Copy the code
Commons Email example:
// Commons Email example
HtmlEmail email = new HtmlEmail();
// Set basic information
email.setHostName("smtp.qq.com");
email.setAuthenticator(new DefaultAuthenticator("[email protected]"."xxxxxxxx"));
email.setFrom("[email protected]");
email.addTo("[email protected]");
email.setSubject("Comprehensive mail with attachments and pictures and body sent by Commons Mail.");
// Generate the image identifier
String cid = email.embed(new File("D:\\commons mail\\images\\5.jpg"));
email.setCharset(EmailConstants.UTF_8);
email.setHtmlMsg( + cid + "\"></html>");
// Extra tips
email.setTextMsg("Your email does not support HTML");
/ / accessories
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("D:\\commons mail\\files\\test.docx");
EmailAttachment attachment2 = new EmailAttachment();
attachment2.setPath("D:\\commons mail\\files\\test2.txt");
email.attach(attachment);
email.attach(attachment2);
/ / send
email.send();
Copy the code
As you can see from the example above, sending complex messages using Commons Email is much easier than using the Java native API.
04. ImageHtmlEmail
The example in the previous chapter shows that HtmlEmail can also send pictures, so what’s the point of ImageHtmlEmail?
HtmlEmail’s embed method is called and its return value is set toOn the SRC TAB, as shown in the following example
// Embed method has multiple overloading methods, support URL, local file, etc
String cid = email.embed(new File("D:\\commons mail\\images\\5.jpg"));
email.setHtmlMsg("<html><img src=\"cid:" + cid + "\"></html>");
Copy the code
ImageHtmlEmail only needs to set the corresponding Resolver. If you send a lot of pictures, this will be a lot easier to use. Let’s take a look at a simple example
// Omit part of the code...
ImageHtmlEmail email = new ImageHtmlEmail();
URL url = new URL("http://example.com");
email.setDataSourceResolver(new DataSourceUrlResolver(url));
email.setHtmlMsg("<img src=\"http://example.com/test.png\"> ...");
// Omit part of the code...
Copy the code
If send pictures of different sources depends on DataSourceCompositeResolver class, is one of the portfolio model implementation, support and set up multiple resolver, direct look at the code examples below
// Omit part of the code...
ImageHtmlEmail email = new ImageHtmlEmail();
// Local path
File file = new File("D:\\commons email");
// The path on the network
URL url = new URL("http://example.com");
/ / class path
String classpath = "META-INF/img";
DataSourceResolver r1 = new DataSourceFileResolver(file);
DataSourceResolver r2 = new DataSourceUrlResolver(url);
DataSourceResolver r3 = new DataSourceClassPathResolver(classpath);
DataSourceResolver[] resolvers = {r1, r2, r3};
// Combine resolvers to receive multiple resolvers
DataSourceResolver compositeResolver = new DataSourceCompositeResolver(resolvers);
email.setDataSourceResolver(compositeResolver);
email.setHtmlMsg("
" +
"<img src=\"D:\\commons email\\t1.png\">" +
"Picture 2:
" +
"<img src=\"http://example.com/t2.png\">" +
"Picture 3:
" +
"<img src=\"META-INF/img/t3.png\">");
// Omit part of the code...
Copy the code
05. Conclusion
Commons Email as a Java Email sending tool class, API is simple and easy to understand, greatly simplifying the complexity of Java mail sending program. It is a good alternative to Java’s own API.
I look forward to your attention as I continue to introduce you to other useful utility libraries in The Commons section.