1. 邮箱设置
在邮箱客户端中开启SMTP服务。
2. Spring Email
①引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
②邮箱参数配置
# MailProperties
spring.mail.host=smtp.sina.com
spring.mail.port=465
spring.mail.username=hellohuohuo@sina.com
spring.mail.password=0789db1cXXXXXX
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
注:这里的密码不是邮箱密码,是申请smtp时,人家给的那个密码。
③使用JavaMailSender发送邮件
创建工具类:
右键com.nowcoder.mycommunity目录 - new Java,起名:Util.MailClient
//邮箱客户端,用于提供发邮件的功能
//需要的信息包含:
//1.发邮件的人(为固定)
//2.收邮件的人; 3. 邮件标题; 4. 邮件内容。
@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());
}
}
}
测试
@SpringBootTest
public class MailTest {
@Autowired
private MailClient mailClient;
@Test
public void testTextMail(){
mailClient.sendMail("1040756130@qq.com","Test","hello, huo");
}
}
3. 使用Thymeleaf发送html邮件
测试方法:
@Autowired
private TemplateEngine templateEngine;
@Test
public void testHtmlMail(){
Context context = new Context();
context.setVariable("username","huohuohuo");
String content = templateEngine.process("/mail/demo",context);
System.out.println(content);
mailClient.sendMail("1040756130@qq.com","Html",content);
}
html:
放在resources/templates/mail/demo.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件示例</title>
</head>
<body>
<p>欢迎你, <span style="color:#ff3d35;" th:text="${username}"></span>!</p>
</body>
</html>