SpringBoot配置郵件服務:html
1.引入jargit
<!-- 郵件 -->github
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>spring
2.配置資源文件,郵箱參數:服務器
#郵件:郵件服務器
spring.mail.host=smtp.163.com
#發件人郵箱
spring.mail.username=xxx@163.com
#受權碼:
spring.mail.password=abc123
#編碼:
spring.mail.default-encoding=UTF-8app
3.準備發送郵件方法:ide
service層讀取配置文件參數,注入JavaMailSenderspring-boot
@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