环境
操作系统:
Windows 10 x64
集成开发环境:
Spring Tool Suite 4
Version: 4.14.0.RELEASE
Build Id: 202203131612
发送邮件
邮箱设置
我使用的 163 邮箱提供的服务。首先,登录 163 邮箱,设置如下:
-
设置 > POP3/SMTP/IMAP
-
开启 IMAP/SMTP 服务:
-
使用你的手机发送短信验证:
-
验证完成,得到授权密码,记住:
-
邮箱服务设置完成:
项目结构
新建 Spring Starter Project,最终项目结构如下:
配置
项目创建完成,pom.xml 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.mk</groupId>
<artifactId>Spring-Boot-Send-Email</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring-Boot-Send-Email</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
修改 application.yml 配置文件,邮件服务配置参数:
server:
port: 8080
spring:
mail:
host: smtp.163.com
username: XXX@163.com
password: XXX
default-encoding: UTF-8
protocol: smtp
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
编码
email.html 模板:
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
</head>
<body>
<p>验证码:<span th:text="${code}">{code}</span></p>
</body>
</html>
提供邮件发送服务的控制器类:
package com.mk.controller;
import java.io.File;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("/email")
@Slf4j
public class EmailController {
@Autowired
private JavaMailSender jms;
@Value("${spring.mail.username}")
private String addresser; // 发信人
private String addressee = "xxx@qq.com"; // 收信人
@Autowired
private TemplateEngine templateEngine;
@RequestMapping("send-simple-email")
public long sendSimpleEmail() {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(addresser);
message.setTo(addressee);
message.setSubject("一封简单的邮件");
message.setText("验证码:1234");
jms.send(message);
} catch (Exception e) {
log.error("Exception: ", e);
}
return System.currentTimeMillis();
}
@GetMapping("send-html-email")
public long sendHtmlEmail() {
try {
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(addresser);
helper.setTo(addressee);
helper.setSubject("一封 HTML 格式的邮件");
String content = "<p style='color: #00ff00;'>验证码:1234</p>";
helper.setText(content, true);
jms.send(message);
} catch (Exception e) {
log.error("Exception: ", e);
}
return System.currentTimeMillis();
}
@GetMapping("send-attachment-email")
public long sendAttachmentEmail() {
try {
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(addresser);
helper.setTo(addressee);
helper.setSubject("一封带附件的邮件");
helper.setText("附件:光头强的个人简历");
FileSystemResource file = new FileSystemResource(new File("F:/temp/光头强的个人简历.pdf"));
helper.addAttachment("光头强的个人简历.pdf", file);
jms.send(message);
} catch (Exception e) {
log.error("Exception: ", e);
}
return System.currentTimeMillis();
}
@GetMapping("send-inline-email")
public long sendInlineEmail() {
try {
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(addresser);
helper.setTo(addressee);
helper.setSubject("一封带静态资源的邮件");
helper.setText("<img src='cid:img' style='width: 70px; height: 100px;' />", true);
helper.addInline("img", new FileSystemResource(new File("F:/temp/光头强.png")));
jms.send(message);
} catch (Exception e) {
log.error("Exception: ", e);
}
return System.currentTimeMillis();
}
@GetMapping("send-template-email")
public long sendTemplateEmail() {
try {
MimeMessage message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(addresser);
helper.setTo(addressee);
helper.setSubject("模板邮件");
Context context = new Context();
context.setVariable("code", "1234");
String template = templateEngine.process("email", context); // 指向模板 templates/email.html
helper.setText(template, true);
jms.send(message);
} catch (Exception e) {
log.error("Exception: ", e);
}
return System.currentTimeMillis();
}
}
测试
依次访问:
- http://localhost:8080/email/send-simple-email
- http://localhost:8080/email/send-html-email
- http://localhost:8080/email/send-attachment-email
- http://localhost:8080/email/send-inline-email
- http://localhost:8080/email/send-template-email
在目标收信人邮箱中,可以收到: