SpringBoot配置邮件服务:
1.引入jar
<!-- 邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置资源文件,邮箱参数:
#邮件:邮件服务器
spring.mail.host=smtp.163.com
#发件人邮箱
spring.mail.username=xxx@163.com
#授权码:
spring.mail.password=abc123
#编码:
spring.mail.default-encoding=UTF-8
3.准备发送邮件方法:
service层读取配置文件参数,注入JavaMailSender
@Value("${spring.mail.username}")
private String sender; //读取配置文件中的参数
@Autowired
private JavaMailSender mailSender; //自动注入的Bean
/**
* 发送普通文本:
* @param to 发送人:
* @param subject 发送标题:
* @param context 发送内容:
*/
@Override
public void sendSimpleMail(String to, String subject, String context) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sender);
message.setTo(to);
message.setSubject(subject);
message.setText(context);
mailSender.send(message);
}
/**
* 发送html:
* @param to 发送人:
* @param subject 发送标题:
* @param context 发送内容:
*/
@Override
public void sendSimpleMailHTML(String to, String subject, String context) {
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(to);
helper.setSubject("标题:发送Html内容");
StringBuffer sb = new StringBuffer();
sb.append("<h1>大标题-h1</h1>")
.append("<p style='color:#F00'>红色字</p>")
.append("<p style='text-align:right'>右对齐</p>");
helper.setText(sb.toString(), true);
} catch (Exception e) {
e.printStackTrace();
}
mailSender.send(message);
}
推荐学习网址:https://github.com/ityouknow/awesome-spring-boot