MailUtil

Overview

Sending emails in Java mainly relies on the javax.mail package, but using it can be cumbersome. Hutool has wrapped it for easier use. Due to its dependence on third-party packages, this tool class is categorized into the extra module.

Usage

Adding Dependencies

Hutool’s dependencies on all third-party libraries are optional, so when using MailUtil, you need to manually add the third-party dependencies.

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

Note: com.sun.mail is an upgraded version of javax.mail, and the package name has changed in the new version.

Email Server Configuration

Create a mail.setting file in the config directory under the classpath (in a standard Maven project, it’s src/main/resources) with the minimum configuration as follows. In this configuration, the SMTP server and username will be identified by the from parameter:

# Sender (must be correct, otherwise the sending will fail)
from = [email protected]
# Password (note that some email services require a separate password for the SMTP service, see the relevant help for details)
pass = q1w2e3

Sometimes, non-standard email servers (such as enterprise email servers) may have different SMTP addresses and ports that are not consistent with the sender’s suffix. Hutool can provide a complete configuration file in such cases:

# SMTP address of the email server, optional, defaults to smtp.<sender's email suffix>
host = smtp.yeah.net
# SMTP port of the email server, optional, defaults to 25
port = 25
# Sender (must be correct, otherwise the sending will fail)
from = [email protected]
# Username, defaults to the sender's email prefix
user = hutool
# Password (note that some email services require a separate authorization code for the SMTP service, see the relevant help for details)
pass = q1w2e3

Note: The email server must support and enable the SMTP protocol. Please refer to the relevant help documentation for details. The sample configuration file provides a yeah.net email account that I registered specifically for testing email functionality. The account password is public and can be used by Hutool users for testing purposes.

Sending Emails

  1. Send a plain text email, with an optional parameter to add multiple attachments:
MailUtil.send("[email protected]", "Test", "Email from Hutool test", false);
  1. Send an HTML-formatted email with attachments, with an optional parameter to add multiple attachments:
MailUtil.send("[email protected]", "Test", "<h1>Email from Hutool test</h1>", true, FileUtil.file("d:/aaa.xml"));
  1. Send emails to multiple recipients, with an optional parameter to specify whether it’s HTML or plain text, and an optional parameter to add multiple attachments:
ArrayList<String> tos = CollUtil.newArrayList(
	"[email protected]", 
	"[email protected]", 
	"[email protected]", 
	"[email protected]");
MailUtil.send(tos, "Test", "Email from Hutool group test", false);

Sending emails is very simple and can be done with just one method. The parameters are explained in order as follows:

  1. tos: The email address of the recipient, which can be a single address or multiple addresses represented by a Collection.
  2. subject: The subject of the email.
  3. content: The body of the email, which can be plain text or HTML content.
  4. isHtml: Whether the content is HTML. If it is, parameter 3 will be recognized as HTML content.
  5. files: Optional: attachments, which can be multiple or none. File objects can be added as the last variable parameter.

Other Features

  1. Custom Mail Server

In addition to using a configuration file to define global account information, the MailUtil.send method also provides overloaded methods that can accept a MailAccount object. This object is a simple Bean that records mail server information.

MailAccount account = new MailAccount();
account.setHost(""smtp.yeah.net");
account.setPort("25");
account.setAuth(true);
account.setFrom("hutool@yeah.net");
account.setUser("hutool");
account.setPass("q1w2e3");

MailUtil.send(account, CollUtil.newArrayList("hutool@foxmail.com"), "测试", "邮件来自Hutool测试", false);
  1. Using SSL Encryption to Send Emails When using QQ or Gmail email addresses, it is necessary to强制enable SSL support. In this case, we only need to modify the configuration file as follows:
# Sender (must be correct, otherwise the sending will fail), "Xiaolei" can be changed arbitrarily, the address in <> must be unique, the following method is also correct
# from = [email protected]
from = Xiaolei<[email protected]>
# Password (note that some email services require a separate password to be set for the SMTP service, see the relevant help for details)
pass = q1w2e3
# Use SSL secure connection
sslEnable = true

By simply adding sslEnable to the original minimal configuration, SSL connection can be established. Of course, this is the simplest configuration, and many parameters have been set to default based on the existing parameters.

The complete configuration file is as follows:

# SMTP address of the mail server
host = smtp.yeah.net
# SMTP port of the mail server
port = 465
# Sender (must be correct, otherwise the sending will fail)
from = [email protected]
# Username (note: if using a foxmail email address, the user here should be the QQ number)
user = hutool
# Password (note that some email services require a separate password to be set for the SMTP service, see the relevant help for details)
pass = q1w2e3
# Use STARTTLS secure connection, STARTTLS is an extension to plain text communication protocols.
starttlsEnable = true

# Use SSL secure connection
sslEnable = true
# Specify the name of the class that implements the javax.net.SocketFactory interface, which will be used to create the SMTP socket
socketFactoryClass = javax.net.ssl.SSLSocketFactory
# If set to true, failure to create a socket using the specified socket factory class will result in the use of a socket created using java.net.Socket. The default value is true.
socketFactoryFallback = true
# Specify the port to connect to when using the specified socket factory. If not set, the default port 456 will be used.
socketFactoryPort = 465

# SMTP timeout duration in milliseconds, the default value is no timeout
timeout = 0
# Socket connection timeout value in milliseconds, the default value is no timeout
connectionTimeout = 0
  1. Instructions for QQ and Foxmail Email Addresses (1) The SMTP password for QQ email is a separately generated authorization code, not your QQ password. For instructions on how to generate it, see Tencent’s help documentation: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256 After generating the authorization code using the help guide, configure as follows:
pass = Your generated authorization code

(2) Foxmail email is essentially an alias of QQ email. You can set up a foxmail email address in your QQ email, but there are some differences in the configuration. In Hutool, the user attribute by default extracts the part before the @ symbol in your email address, but this is not valid for foxmail email addresses. It needs to be configured separately as the QQ number associated with it or as the XXXX part of [email protected]. That is:

host = smtp.qq.com
from = [email protected]
user = QQ number associated with foxmail email or XXXX part of [email protected]
...

(3) The user of Aliyun email is the full address of the email, that is, [email protected]

  1. For QQ email (foxmail) PKIX path building failed error (since 5.6.4)

Some users have reported encountering the following error when sending emails:

cn.hutool.extra.mail.MailException: MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465
...
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

This error may be caused by the need for SSL verification. We can manually skip this verification as follows:

MailAccount mailAccount = new MailAccount();
mailAccount.setAuth(true);
mailAccount.setSslEnable(true);
...
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
mailAccount.setCustomProperty("mail.smtp.ssl.socketFactory", sf);

Mail mail = Mail.create(mailAccount)
    .setTos("[email protected]")
 .setTitle("Email Verification")
 .setContent("Your verification code is: <h3>2333</h3>")
 .setHtml(true)
 .send();