Quickly Integrate Email Sending in Spring Boot with JavaMailSender
This tutorial walks you through setting up Spring Boot to send simple and complex emails, covering SMTP/IMAP/POP3 basics, JavaMailSender configuration, code examples for plain text and attachment emails, auto‑configuration details, a REST controller, Thymeleaf UI, testing steps, and common SMTP error codes.
Learning Objective
Quickly master the core logic of email services and everyday enterprise email usage.
What is SMTP?
Simple Mail Transfer Protocol (SMTP) is a set of rules for transferring mail from a source address to a destination address, requiring authentication to prevent spam.
What is IMAP?
Internet Message Access Protocol (IMAP) allows retrieving and managing mail on the server, supporting two‑way synchronization.
What is POP3?
Post Office Protocol 3 (POP3) enables downloading mail from the server, typically removing it after download.
Difference Between IMAP and POP3
IMAP syncs actions (read, delete) back to the server, while POP3 does not.
JavaMailSender and JavaMailSenderImpl
Spring provides the JavaMailSender interface and its JavaMailSenderImpl implementation for email integration.
Sending a Simple Email
Inject JavaMailSenderImpl and call send with a SimpleMailMessage:
@Autowired
private JavaMailSenderImpl mailSender;
public void sendSimple() {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setFrom("[email protected]");
msg.setTo("[email protected]");
msg.setSubject("Happy New Year");
msg.setText("新年快乐!");
mailSender.send(msg);
}Sending a Complex Email with Attachments
Use MimeMessageHelper to build a MimeMessage that supports HTML, inline resources, and attachments:
MimeMessage mime = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mime, true);
helper.setFrom("[email protected]");
helper.setTo("[email protected]");
helper.setSubject("Happy New Year");
helper.setText("新年快乐!", true);
helper.addInline("doge.gif", new File("xx/xx/doge.gif"));
helper.addAttachment("work.docx", new File("xx/xx/work.docx"));
mailSender.send(mime);Auto‑Configuration
Spring Boot automatically configures JavaMailSenderImpl via MailSenderPropertiesConfiguration which reads MailProperties bound to spring.mail properties.
@Configuration
public class MailSenderPropertiesConfiguration {
private final MailProperties properties;
public MailSenderPropertiesConfiguration(MailProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
public JavaMailSenderImpl mailSender() {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
// applyProperties(sender);
return sender;
}
}MailProperties Class
@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {
private String host;
private Integer port;
private String username;
private String password;
private String protocol = "smtp";
private Charset defaultEncoding = StandardCharsets.UTF_8;
private Map<String, String> properties = new HashMap<>();
// getters and setters omitted
}Enable Email Service
Log into a 163.com mailbox, enable POP3/SMTP/IMAP, and obtain an authorization code.
Project Setup
Create a Spring Boot project with the following dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
</dependencies>Application Configuration
spring:
mail:
host: smtp.163.com
username: socks
password: 123456
properties:
from: [email protected]
thymeleaf:
cache: false
prefix: classpath:/views/
servlet:
multipart:
max-file-size: 10MB
max-request-size: 50MBMail Service Implementation
The service validates required fields, builds MimeMessage, handles CC/BCC, adds attachments, sets sent date, logs success or failure, and returns a MailVo object.
@Service
public class MailService {
@Autowired
private JavaMailSenderImpl mailSender;
private Logger logger = LoggerFactory.getLogger(getClass());
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;
}
}
// checkMail, sendMimeMail, saveMail methods omitted for brevity
}Controller and View
A MailController provides the index page and a POST endpoint to receive the form data.
@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);
}
}Thymeleaf HTML form (simplified):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>发送邮件</title>
<link th:href="@{/webjars/bootstrap/css/bootstrap.min.css}" rel="stylesheet" type="text/css"/>
</head>
<body>
<form id="mailForm" th:action="@{/mail/send}" method="post" enctype="multipart/form-data">
<label>邮件发信人:</label>
<input th:value="${from}" readonly="readonly"/>
<label>邮件收信人:</label>
<input name="to"/>
<label>邮件主题:</label>
<input name="subject"/>
<label>邮件内容:</label>
<textarea name="text"></textarea>
<label>邮件附件:</label>
<input type="file" name="files" multiple/>
<button type="submit">发送邮件</button>
</form>
</body>
</html>Testing
Run the application, open http://localhost:8080, fill the form, and click “发送邮件”. Verify the email and any attachments in the recipient mailbox.
Common Failure Codes
Typical SMTP error codes returned by NetEase mail servers:
421 – temporary connection block due to abnormal sending behavior.
450 – command or recipient limit exceeded, authentication required, or IP not whitelisted.
451 – temporary rejection because of spam characteristics or authentication failures.
500 – syntax errors or policy violations (e.g., SPF, DMARC).
552 – illegal attachment type or message size too large.
553 – null sender or authentication required.
554 – permanent rejection due to spam, mismatched envelope, or blacklisted IP.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
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.
