Java Email Sending Utility Using Spring and JavaMail
This article provides a step‑by‑step guide on configuring JavaMail dependencies, setting SMTP properties, implementing an EmailUtils helper class, and testing the email sending functionality with a Spring REST controller, enabling developers to send HTML emails with optional attachments.
The post shares a complete Java tutorial for sending emails via SMTP using Spring and the JavaMail library. It begins with the required Maven dependency for javax.mail :
com.sun.mail
javax.mail
1.6.0Next, the necessary SMTP configuration properties are listed, which should be placed in the application’s configuration file:
mail.smtp.auth=true
mail.transport.protocol=smtp
mail.send.charset=UTF-8
mail.smtp.port=465
mail.is.ssl=true
mail.host=smtp.163.com
[email protected]
mail.auth.password=
mail.smtp.timeout=5000The core of the tutorial is the EmailUtils component. It reads the above properties at startup, builds a JavaMailSenderImpl instance, and provides a static sendEmail method that supports multiple recipients, CC, HTML content, and file attachments. The implementation handles SSL socket factories, constructs a MimeMessage , and logs any failures.
package cn.aduu.utils;
import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Email utility class for sending messages.
*/
@Component
public class EmailUtils {
private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);
@Autowired
private Environment env;
private static String auth;
private static String host;
private static String protocol;
private static int port;
private static String authName;
private static String password;
private static boolean isSSL;
private static String charset;
private static String timeout;
@PostConstruct
public void initParam() {
auth = env.getProperty("mail.smtp.auth");
host = env.getProperty("mail.host");
protocol = env.getProperty("mail.transport.protocol");
port = env.getProperty("mail.smtp.port", Integer.class);
authName = env.getProperty("mail.auth.name");
password = env.getProperty("mail.auth.password");
charset = env.getProperty("mail.send.charset");
isSSL = env.getProperty("mail.is.ssl", Boolean.class);
timeout = env.getProperty("mail.smtp.timeout");
}
/**
* Send an email.
* @param subject Email subject
* @param toUsers Recipients
* @param ccUsers CC recipients (optional)
* @param content HTML content
* @param attachfiles List of attachments (name & file path)
*/
public static boolean sendEmail(String subject, String[] toUsers, String[] ccUsers,
String content, List
> attachfiles) {
boolean flag = true;
try {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
javaMailSender.setUsername(authName);
javaMailSender.setPassword(password);
javaMailSender.setDefaultEncoding(charset);
javaMailSender.setProtocol(protocol);
javaMailSender.setPort(port);
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", auth);
properties.setProperty("mail.smtp.timeout", timeout);
if (isSSL) {
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
}
javaMailSender.setJavaMailProperties(properties);
MimeMessage mailMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);
messageHelper.setTo(toUsers);
if (ccUsers != null && ccUsers.length > 0) {
messageHelper.setCc(ccUsers);
}
messageHelper.setFrom(authName);
messageHelper.setSubject(subject);
messageHelper.setText(content, true);
if (attachfiles != null && attachfiles.size() > 0) {
for (Map
attachfile : attachfiles) {
String attachfileName = attachfile.get("name");
File file = new File(attachfile.get("file"));
messageHelper.addAttachment(attachfileName, file);
}
}
javaMailSender.send(mailMessage);
} catch (Exception e) {
logger.error("发送邮件失败!", e);
flag = false;
}
return flag;
}
}To verify the utility, a simple Spring REST controller is provided. Calling the /sendEmail endpoint triggers EmailUtils.sendEmail with a test HTML message.
package cn.aduu.web;
import cn.aduu.utils.EmailUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Test controller for sending email.
*/
@RestController
public class EmailController {
private static final Logger logger = LoggerFactory.getLogger(EmailController.class);
@RequestMapping("sendEmail")
public String sendEmail() throws JsonProcessingException {
boolean isSend = EmailUtils.sendEmail(
"这是一封测试邮件",
new String[]{"[email protected]"},
null,
"
百度一下,你就知道
",
null);
return "发送邮件:" + isSend;
}
}The article concludes with a friendly reminder to like and share if the content was helpful, and includes promotional images and links unrelated to the technical content.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.