在项目中会遇到注册登陆功能,在注册后会给用户发送包含注册及激活信息的邮件。
这里以新浪邮箱为例。
步骤
1.在邮箱中开启服务
进入邮箱后在设置中开启smtp服务,记住授权码,后面会用。
2.pom文件添加依赖
<!-- 邮件服务-->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
3.写properties文件
#MailProperties
#一般邮件服务端口号是465,username为邮件账户名,password为邮箱的授权码,不是开始的密码,否则会报错
spring.mail.host=smtp.sina.com
spring.mail.port=465
spring.mail.username=abc@sina.com
spring.mail.password=123
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
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());
}
}
}
5.写测试
@SpringBootTest
@ContextConfiguration(classes =写你自己的项目启动类.class)
public class MailTest {
@Autowired
private MailClient mailClient;
//这里用了thymeleaf的模板
@Autowired
private TemplateEngine templateEngine;
@Test
public void testHtmlMail(){
Context context = new Context();
context.setVariable("username","Jackson");
String content = templateEngine.process("mail/mailDemo.html", context);
mailClient.sendMail("目标邮件地址","主题", content);
}
}
6.写发送内容
既然上面采用了发送html的方式,还需要写好你的HTML模板文件,包含注册信息或者你想让用户知道的信息,这个自由发挥了=w=
比如我的写在了templates目录下的mail下的mailDemo文件中。剩下的不做赘述。