Spring Boot Email Integration Tutorial: Using JavaMailSenderImpl to Send Simple and MIME Emails
This article provides a step‑by‑step guide for integrating email functionality into a Spring Boot application, covering SMTP/IMAP/POP3 basics, configuring JavaMailSenderImpl, sending simple and MIME messages with attachments, and includes full source code examples and troubleshooting tips.
Spring Boot makes it straightforward to add email capabilities to a Java backend. This tutorial walks through the essential concepts of SMTP, IMAP, and POP3, explains how to configure Spring Boot’s JavaMailSenderImpl , and demonstrates sending both simple text emails and complex MIME messages with attachments.
Learning Objectives
Understand the core logic of email services and enterprise email daily operations.
What is SMTP?
Simple Mail Transfer Protocol (SMTP) is the standard for transmitting email from a source address to a destination address. Authentication requires a username and password to prevent spam.
What is IMAP?
Internet Message Access Protocol (IMAP) allows clients to retrieve and manage email messages on the server, supporting two‑way synchronization.
What is POP3?
Post Office Protocol 3 (POP3) enables clients to download emails, typically removing them from the server after retrieval.
JavaMailSender and JavaMailSenderImpl
Spring provides the JavaMailSender interface and its default implementation JavaMailSenderImpl for easy email integration.
Sending a Simple Email
@Autowired
private JavaMailSenderImpl mailSender;
public void sendSimpleMail() throws MessagingException {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("[email protected]");
message.setTo("[email protected]");
message.setSubject("Happy New Year");
message.setText("新年快乐!");
mailSender.send(message);
}Sending a MIME Email with Attachments
@Autowired
private JavaMailSenderImpl mailSender;
public void sendMimeMail(MailVo mailVo) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(mailVo.getFrom());
helper.setTo(mailVo.getTo().split(","));
helper.setSubject(mailVo.getSubject());
helper.setText(mailVo.getText());
if (!StringUtils.isEmpty(mailVo.getCc())) {
helper.setCc(mailVo.getCc().split(","));
}
if (!StringUtils.isEmpty(mailVo.getBcc())) {
helper.setBcc(mailVo.getBcc().split(","));
}
if (mailVo.getMultipartFiles() != null) {
for (MultipartFile file : mailVo.getMultipartFiles()) {
helper.addAttachment(file.getOriginalFilename(), file);
}
}
mailSender.send(mimeMessage);
}Mail Service Implementation
@Service
public class MailService {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private JavaMailSenderImpl mailSender;
public MailVo sendMail(MailVo mailVo) {
try {
checkMail(mailVo);
sendMimeMail(mailVo);
return saveMail(mailVo);
} catch (Exception e) {
logger.error("发送邮件失败:", e);
mailVo.setStatus("fail");
mailVo.setError(e.getMessage());
return mailVo;
}
}
private void checkMail(MailVo mailVo) {
if (StringUtils.isEmpty(mailVo.getTo())) {
throw new RuntimeException("邮件收信人不能为空");
}
if (StringUtils.isEmpty(mailVo.getSubject())) {
throw new RuntimeException("邮件主题不能为空");
}
if (StringUtils.isEmpty(mailVo.getText())) {
throw new RuntimeException("邮件内容不能为空");
}
}
private void sendMimeMail(MailVo mailVo) {
try {
MimeMessageHelper helper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
helper.setFrom(getMailSendFrom());
helper.setTo(mailVo.getTo().split(","));
helper.setSubject(mailVo.getSubject());
helper.setText(mailVo.getText());
// cc, bcc, attachments handling omitted for brevity
mailSender.send(helper.getMimeMessage());
mailVo.setStatus("ok");
logger.info("发送邮件成功:{}->{}", mailVo.getFrom(), mailVo.getTo());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getMailSendFrom() {
return mailSender.getJavaMailProperties().getProperty("from");
}
private MailVo saveMail(MailVo mailVo) {
// Persist mail record to database (implementation omitted)
return mailVo;
}
}Controller and Front‑End Page
@RestController
public class MailController {
@Autowired
private MailService mailService;
@GetMapping("/")
public ModelAndView index() {
ModelAndView mv = new ModelAndView("mail/sendMail");
mv.addObject("from", mailService.getMailSendFrom());
return mv;
}
@PostMapping("/mail/send")
public MailVo sendMail(MailVo mailVo, MultipartFile[] files) {
mailVo.setMultipartFiles(files);
return mailService.sendMail(mailVo);
}
}The accompanying Thymeleaf template sendMail.html provides a simple UI for entering the sender, recipient, subject, body, and attachments, and uses jQuery AJAX to post the form data to the backend.
Common Failure Codes
The article also lists typical SMTP error codes returned by NetEase mail servers (e.g., 421, 450, 451, 500, 550, 552, 553, 554) and explains their meanings for troubleshooting.
By following this guide, developers can quickly set up reliable email sending in their Spring Boot projects, customize the mail content, handle attachments, and diagnose common delivery issues.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.