添加依赖包
<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>
配置文件
##mail
spring.mail.properties.smtp.ssl.enable=true
#发送邮件服务器
spring.mail.host=smtp.163.com
spring.mail.username=xxx@163.com
spring.mail.password= yourpassword
spring.mail.port=465
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.timeout=25000
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8
mail.fromMail.addr=linkgroup_server@163.com
接口类
package com.linkgroup.service;
public interface MailService {
void sendHtmlMail(String to, String subject, String content, String filePath);
void sendHtmlMail(String to, String subject, String content);
void sendCode(String to, String action);
}
实现类(这里要改成自己的html模板)
package com.linkgroup.service;
import com.linkgroup.util.VerCodeGenerateUtil;
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.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.time.Duration;
@Component
public class MailServiceImpl implements MailService {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private TemplateEngine templateEngine;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
private JavaMailSender mailSender;
@Value("${mail.fromMail.addr}")
private String from;
@Override
public void sendHtmlMail(String to, String subject, String content, String filePath) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (filePath != null) {
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
}
mailSender.send(message);
logger.info("html邮件发送成功");
} catch (MessagingException e) {
logger.error("发送html邮件时发生异常!", e);
}
}
@Override
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
logger.info("html邮件发送成功");
} catch (MessagingException e) {
logger.error("发送html邮件时发生异常!", e);
}
}
@Override
public void sendCode(String to, String action) {
String verCode = VerCodeGenerateUtil.generateVerCode();
redisTemplate.opsForValue().set(to, verCode, Duration.ofMinutes(5));
Context context = new Context();
context.setVariable("action", action);
context.setVariable("code", verCode);
String emailContent = templateEngine.process("sendCode", context);
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject("主题:验证码");
helper.setText(emailContent, true);
mailSender.send(message);
logger.info("html邮件发送成功");
} catch (MessagingException e) {
logger.error("发送html邮件时发生异常!", e);
}
}
}
测试类
package com.linkgroup;
import com.linkgroup.service.EmailService;
import com.linkgroup.service.MailService;
import com.linkgroup.util.VerCodeGenerateUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.time.Duration;
@SpringBootTest
class LinkgroupApplicationTests {
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
@Autowired
private EmailService emailService;
@Test
void contextLoads() {
emailService.sendEmailVerCode("xxx@163.com", VerCodeGenerateUtil.generateVerCode());
emailService.sendEmailVerCode("xxx@qq.com", VerCodeGenerateUtil.generateVerCode());
}
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
void set(){
Integer i = 0;
while ( i <= 5 ){
String verCode = VerCodeGenerateUtil.generateVerCode();
redisTemplate.opsForValue().set(i.toString(), verCode, Duration.ofMinutes(5));
System.out.println(redisTemplate.opsForValue().get(i.toString()));
i++;
}
}
@Test
public void sendTemplateMail() {
Context context = new Context();
context.setVariable("siteTitle", "xxx");
context.setVariable("permalink", "xxx");
context.setVariable("title", "xx");
String emailContent = templateEngine.process("sendMail", context);
String filePath="E:\\workspace\\javaWorkspace\\spring-boot-learning\\spring-boot-21-schedule-mail\\doc\\test.log";
mailService.sendHtmlMail("xxx@163.com","主题:这是模板邮件",emailContent, filePath);
}
@Test
public void sendTemplateMail2() {
mailService.sendCode("xxx@163.com","注册账号...");
}
}