SpringBoot发送邮件的方法
作者:互联网
1. 导入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.6.3</version>
</dependency>
2. 打开邮箱设置
3. 编写配置文件
spring.mail.host=smtp.qq.com
spring.mail.username=用户名
spring.mail.password=这里填邮箱的授权码,不是密码!
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
4. 完成发送邮件功能
@Component
public class MailClient {
//java提供的发送邮件的接口
@Autowired
private JavaMailSender mailSender;
//将配置文件中邮件发送方的邮箱地址配置到类中
@Value("${spring.mail.username}")
private String from;
/**
*
* @param to 接收方
* @param subject 标题
* @param content 内容
*/
public void sendMail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
try {
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);//设置为true: 开启发送html页面功能
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
5. 测试
public class MailUtilTest {
@Autowired
private MailUtil mailUtil;
//模板引擎,用来解析thymeleafs下的html文件
@Autowired
private TemplateEngine templateEngine;
/*
简单的测试,只是发送一些文本内容:“发送成功”
*/
@Test
public void test1() {
mailUtil.sendMail("xxxxxx@163.com", "TEST", "发送成功!");
}
/*
常用:发送html页面
*/
@Test
public void test2() {
Context context = new Context();
//设置html中参数
context.setVariable("username", "吴京");
//将html和context封装成一个字符串
String content = templateEngine.process("/mail/demo", context);
//发送邮件
mailUtil.sendMail("xxxxxxx@163.com", "TEST", content);
}
}
标签:content,SpringBoot,helper,spring,发送,mail,邮件,String 来源: https://www.cnblogs.com/timber324/p/16028838.html