Spring Boot实现仿博客园发送通知邮件

 邮件服务已经是基础性服务了 ,是网站的必备功能之一,当注册了某些网站的时候,邮箱里通常会收到一封注册成功通知邮件或者点击激活账号的邮件,博客园也是如此。本文使用Spring Boot,通过QQ邮箱来模仿博客园发送一封通知邮件。

博客园发送的“欢迎您加入博客园”的主题邮件如图所示。这种通知邮件,只有登录用户名在变化,其它邮件内容均不变,很适合用邮件模板来处理。

模板可以实现显示与数据分离,将模板文件和数据通过模板引擎生成最终的HTML代码。

Thymeleaf是一个适用于Web和独立环境的现代服务器端Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本。Thymeleaf由于使用了标签属性做为语法,模版页面直接用浏览器渲染,与其它模板引擎(比如Freemaker)相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。

Thymeleaf作为Spring官方推荐的模板引擎,Spring boot对Thymeleaf支持比较友好,配置简单,这里使用Thymeleaf作为模板引擎。

下面正式开始实现仿博客园发送通知邮件。

1. pom.xml添加邮件和模板相关依赖

复制代码
        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-mail</artifactId>        </dependency>                <dependency>            <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-thymeleaf</artifactId>        </dependency>
复制代码

2. application.property配置邮箱和thymelea模板

我使用的是QQ邮箱,需要获得QQ邮箱的授权码。

关于QQ邮箱生成授权码:进入QQ邮箱 --> 邮箱设置 --> 账户 -->  POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 --> 生成授权码 --> 手机发送验证短信 -->得到授权码
复制代码
spring.mail.host=smtp.qq.com spring.mail.username=QQ邮箱 spring.mail.password=授权码 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true   spring.mail.properties.mail.smtp.starttls.required=true    #thymelea模板配置 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.servlet.content-type:text/html #热部署文件,页面不产生缓存,及时更新 spring.thymeleaf.cache=false spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/**
复制代码

3. 编写Service及其实现

Service中有两个方法:

sendSimpleMail用于发送简单的文本邮件,是一个比较基础的案例。

sendHtmlMail用于发送HTML邮件,发送通知邮件用的就是这个方法。其实模板邮件也就是HTML邮件中的一个子类。

MailService:

复制代码
public interface MailService {     public void sendSimpleMail(String to, String subject, String  content);     public void sendHtmlMail(String to, String subject, String  content); }
复制代码

MailServiceImpl:

复制代码
@Component public class MailServiceImpl implements MailService {      private final Logger logger =  LoggerFactory.getLogger(this.getClass());      @Autowired     private JavaMailSender mailSender;      @Value("${spring.mail.username}")     private
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信