- 邮箱控制
- 启用客户端 SMTP服务
Spring Email
导入依赖的 jar 包
<!-- 导入发邮件的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.6.2</version>
</dependency>
邮箱参数设置
# MailProperties
spring.mail.host=smtp.sina.com
spring.mail.username=xxx@xxx.com
spring.mail.password=xxxxxx
spring.mail.protocol=smtp
spring.mail.properties.mail.smtp.ssl.enable=true
使用 JavaMailSender 发送邮件:封装一个工具类MailClient ```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component;
import javax.mail.MessagingException; import javax.mail.internet.MimeMessage;
@Component public class MailClient { private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
public void sendMail(String to,String subject,String content) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
logger.error("发送邮件失败:"+e.getMessage());
}
}
}
- 模板引擎
- 使用 Thymeleaf 发送 HTML 邮件
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件示例</title>
</head>
<body>
<p>欢迎你,<span th:text="${username}"></span></p>
</body>
</html>
测试使用相应的HTML模板发送邮件
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = CommunityApplication.class)
@SpringBootTest
public class MailTests {
// 注入已经封装好的工具类
@Autowired
private MailClient mailClient;
// 注入模板引擎
@Autowired
private TemplateEngine templateEngine;
@Test
public void testSendMail() {
mailClient.sendMail("2218877219@qq.com","SpringBootTest","hello");
}
@Test
public void testHtmlMail() {
Context context = new Context();
context.setVariable("username","Ethereal");
// 使用 resources/templates/mail/demo.html作为模板发送邮件
String content = templateEngine.process("/mail/demo",context);
System.out.println(content);
mailClient.sendMail("2218877219@qq.com","HtmlMailTest","welcome");
}
}