(入门SpringBoot)SpringBoot发送邮件(十一)
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);
}
上一篇: 经验分享:如何让你的网站更好用