- 邮箱设置:启用客户端SMTP服务.
- Spring Email
- 导入jar包
- 邮箱参数配置
- 使用JavaMailSender 发送邮件。
- 模板引擎
- 使用Thymeleaf 发送HTML邮件
spring的官网
网易 163、126免费邮箱目前不直接开放smtp、pop3服务;因此注册一个新浪邮箱(ps:邮箱注册很麻烦,不如其他邮箱好用)
- 使用Thymeleaf 发送HTML邮件
下载相关的依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.7.3</version>
</dependency>
在application.properties中配置
写代码发送邮件
编写工具类
package com.nowcoder.community.util;
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//通用的bean,在那个层次都可以用
public class MailClient {
private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
@Autowired
private JavaMailSender mailSender;//看情况,不影响运行此处先不修改,可能是idea工具的原因
@Value("${spring.mail.username}")
private String from;//发送人
public void sendMail(String to, String subject, String content) {
try {
//发邮件的逻辑
MimeMessage message = mailSender.createMimeMessage();//message在这一步还是空的
MimeMessageHelper helper = new MimeMessageHelper(message);//传入到helper,进一步构建
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);//不加html参数,则只支持文本,此处为了支持html文件
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
logger.error("发送邮件失败:" + e.getMessage());
}
}
}
测试类测试
package com.nowcoder.community;
import com.nowcoder.community.util.MailClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {
@Autowired
private MailClient mailClient;
@Autowired
private TemplateEngine templateEngine;//注入模板殷勤bean
@Test//执行了就会发送
public void testTextMail() {
mailClient.sendMail("lihonghe@nowcoder.com", "TEST", "Welcome.");
}
@Test
public void testHtmlMail() {
//使用Thymeleaf 发送HTML邮件
Context context = new Context();//传给模板的参数
context.setVariable("username", "sunday");//构建参数
String content = templateEngine.process("/mail/demo", context);//经过process以后,会生成一个动态html
System.out.println(content);
//发邮件的过程
mailClient.sendMail("lihonghe@nowcoder.com", "HTML", content);
}
}
使用Thymeleaf 发送HTML邮件
在测试类中写代码:发送一个动态页面