700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 史上最简单 利用Spring-boot快速搭建邮件发送服务!

史上最简单 利用Spring-boot快速搭建邮件发送服务!

时间:2023-06-21 23:46:28

相关推荐

史上最简单 利用Spring-boot快速搭建邮件发送服务!

1、前言

邮件发送功能非常普遍,用户注册验证、重要通知、调查问卷等都会用到邮件发送。

而Spring-boot进一步简化了Java邮件配置,一个简单邮件(不含附件)发送的核心代码仅为7行,非常适合新手入门。

2、前期准备

1、本文全程使用163邮箱作为发件邮箱,需要开启邮箱的POP3/SMTP服务。

如使用QQ邮箱,也需要进行同样设置,并补充授权码。注意:使用第三方工具发送邮件授权码即为QQ邮箱发件密码,而不是QQ邮箱原始密码。详细设定请参考https://service./cgi-bin/help?subtype=1&&no=1001256&&id=28

2、本文将从以下三个方面进行讲解:

①发送简单邮件(不含附件)

②发送带附件的邮件(进阶)

③使用Thymeleaf模板构建邮件模板发送邮件(进阶,了解即可)

3、发送简单邮件

1、创建一个demomail项目,勾选 Spring Web和Java Mail Sender依赖。项目依赖均在pom.xml集中管理,后续可以增加/修改。

2、我们在src-->main-->java-->com.example.demomail下创建一个package(文件夹),命名为Service,再创建一个package,命名为Controller。

我们又分别在Service下面创建一个MailService类,在Controller下面创建一个MailController类,项目结构树如下图。

3、在application.properties中进行邮件基本信息的配置。Spring-boot最核心的就是使用配置从而简化操作。

我们将下方配置文件复制到application.properties中。将发件邮箱修改为你个人163邮箱的配置。

#重新定义一个服务端口,默认是8080server.port=8081#邮箱基本信息配置--------------------------------------#发件服务器地址spring.mail.host=#发件服务器端口,163邮箱为465spring.mail.port=465#发件箱账号,我的发件邮箱为lulc@spring.mail.username=lulc(需要修改)#发件箱密码,163邮箱为发件邮箱密码,QQ邮箱为申请的授权码spring.mail.password=***1984***(需要修改)#邮箱编码设置spring.mail.default-encoding=utf-8#SSL连接配置spring.mail.properties.mail.smtp.socketFactory.class=.ssl.SSLSocketFactory#后台是否打开DEBUG模式,测试可以打开,正式应用改为falsespring.mail.properties.mail.debug=true#邮箱基本信息配置完毕--------------------------------------

4、接下来我们完成MailService核心代码,JavaMailSender是Spring-boot在MailSenderPropertiesConfiguration类中配置好的,该类在Mail自动配置类MailSenderAutoConfiguration中导入,因此这里直接通过@Autowired注入JavaMailSender就可以使用了。

SendSimpleMail方法的5个参数分别表示邮件发送者、收件人、抄送人、邮件主题和邮件内容。

package com.example.demomail.Service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.ponent;@Componentpublic class MailService {@AutowiredJavaMailSender sender;//直接注入JavaMailSenderpublic void sendmail(String from, String to, String cc, String subject, String content) {SimpleMailMessage mail = new SimpleMailMessage();mail.setFrom(from);//发送者mail.setTo(to);//收件人mail.setCc(cc);//抄送人mail.setSubject(subject);//邮件主题mail.setText(content);//邮件内容sender.send(mail);//发送邮件}}

5、最后我们完善一下MailController,就可以进行测试了。

package com.example.demomail.Controller;import com.example.demomail.Service.MailService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class MailController {@AutowiredMailService service;//注入刚才写好的MailService@GetMapping("/mail")//等同于@RequestMapping(method = RequestMethod.GET)public String sendmail(){service.sendmail("lulc@","182305213@","lulc@","会议通知","请于下午三点在1号会议室参加民主生活会");return "邮件发送成功!";}}

6、右键DemomailApplication,点击Run DemomailApplication,运行程序。打开浏览器输入网址:http://localhost:8081/mail

网页显示:邮件发送成功!IDE也会有成功提示,QQ邮箱也收到了会议通知的邮件。

当你第一次使用代码发送邮件并成功收到了邮件提示,是不是很激动!

4、发送带附件的邮件(进阶)

1、要发送一个带附件的邮件也非常容易,我们使用MimeMessageHelper简化邮件配置,它的构造方法的第二个参数true表示构造一个multipart类型的邮件,即包含多个正文、附件、内嵌资源,表现形式更加丰富。最后通过addAttachment方法添加附件。

我们在MailService中继续添加代码,这里我们以多附件为例。

package com.example.demomail.Service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.ponent;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import java.io.File;@Componentpublic class MailService {@AutowiredJavaMailSender sender;//直接注入JavaMailSender//发送简单邮件public void sendmail(String from, String to, String cc, String subject, String content) {SimpleMailMessage mail = new SimpleMailMessage();mail.setFrom(from);//发送者mail.setTo(to);//收件人mail.setCc(cc);//抄送人mail.setSubject(subject);//邮件主题mail.setText(content);//邮件内容sender.send(mail);//发送邮件}//发送带多附件的邮件 File[] files表示附件集public void sendfilemail(String from, String to, String cc, String subject, String content, File[] files) {try {MimeMessage mimeMessage = sender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);//第二个参数truehelper.setFrom(from);helper.setTo(to);helper.setCc(cc);helper.setSubject(subject);helper.setText(content);//循环添加多附件for (int i = 0; i < files.length; i++) {helper.addAttachment(files[i].getName(), files[i]);}sender.send(mimeMessage);} catch (MessagingException e) {e.printStackTrace();}}}

2、我们在MailController中继续添加代码,就可以测试了。

package com.example.demomail.Controller;import com.example.demomail.Service.MailService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.io.File;@RestControllerpublic class MailController {@AutowiredMailService service;//注入刚才写好的MailService//简单邮件@GetMapping("/mail")//等同于@RequestMapping(method = RequestMethod.GET)public String sendmail(){service.sendmail("lulc@","182305213@","lulc@","会议通知","请于下午三点在1号会议室参加民主生活会");return "邮件发送成功!";}//多附件有邮件@GetMapping("/mailfile")public String sendfilemail(){File[] files =new File[2];//表明有两个附件files[0] =new File("D:\\会议内容.docx");//附件分别存放在D盘根目录files[1] =new File("D:\\会议议程.xlsx");service.sendfilemail("lulc@","182305213@","lulc@","会议通知","请于下午三点在1号会议室参加民主生活会,详见附件",files);return"带附件邮件发送成功!";}}

3、右键DemomailApplication,点击Run DemomailApplication,运行程序。打开浏览器输入网址:http://localhost:8081/mailfile

带附件邮件发送成功!

5、使用Thymeleaf模板构建邮件模板发送邮件(进阶,了解即可)

1、对于复杂样式邮件,如果采用HTML字符串拼接的方式,不但容易出错,且不易于维护,而使用HTML模板可以很好的解决这一问题。这里我们采用Thymeleaf作为邮件构建的模板,首先添加Thymeleaf依赖,参考3.1介绍。

其次创建相应的的邮件模板mailtemplate.html,Thymeleaf模板默认位置是在resource/templates目录下。

我们以邮箱激活为场景,mailtemplate.html代码如下:

其中用户名${username}和性别${gender}为动态赋值。

<!DOCTYPE html><html lang="en" xmlns:th=""><head><meta charset="UTF-8"><title>thymeleaf邮件</title></head><body><div>邮箱激活</div><div>您的注册信息是<table border="1"><tr><td>用户名</td><td th:text="${username}"></td></tr><tr><td>性别</td><td th:text="${gender}"></td></tr></table></div><div><a href="">核对无误请点击本链接激活</a></div></body></html>

2、我们在MailService中继续添加代码,和发送多附件邮件的代码基本一致。

package com.example.demomail.Service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.ponent;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import java.io.File;@Componentpublic class MailService {@AutowiredJavaMailSender sender;//直接注入JavaMailSender//发送简单邮件public void sendmail(String from, String to, String cc, String subject, String content) {SimpleMailMessage mail = new SimpleMailMessage();mail.setFrom(from);//发送者mail.setTo(to);//收件人mail.setCc(cc);//抄送人mail.setSubject(subject);//邮件主题mail.setText(content);//邮件内容sender.send(mail);//发送邮件}//发送带多附件的邮件 File[] files表示附件集public void sendfilemail(String from, String to, String cc, String subject, String content, File[] files) {try {MimeMessage mimeMessage = sender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);//第二个参数truehelper.setFrom(from);helper.setTo(to);helper.setCc(cc);helper.setSubject(subject);helper.setText(content);//循环添加多附件for (int i = 0; i < files.length; i++) {helper.addAttachment(files[i].getName(), files[i]);}sender.send(mimeMessage);} catch (MessagingException e) {e.printStackTrace();}}//thymeleaf作为模板发邮件public void sendthymeleafmail(String from, String to, String cc, String subject, String content,File[] files) {try {MimeMessage mail2 = sender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mail2 , true);helper.setFrom(from);helper.setTo(to);helper.setCc(cc);helper.setSubject(subject);helper.setText(content,true);//多附件for (int i = 0; i < files.length; i++) {helper.addAttachment(files[i].getName(), files[i]);}sender.send(mail2);} catch (MessagingException e) {e.printStackTrace();}}}

3、我们在MailController中继续添加代码,就可以测试了。

Thymeleaf提供了TemplateEngine来对模板进行渲染,将HTML转化为Content邮件内容,此时需要注入TemplateEngin,将HTML转化为htmlcontent。

动态赋值我们通过Context构造模板中变量需要的值。

package com.example.demomail.Controller;import com.example.demomail.Service.MailService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import org.thymeleaf.TemplateEngine;import org.thymeleaf.context.Context;import java.io.File;@RestControllerpublic class MailController {@AutowiredMailService service;//注入刚才写好的MailService//简单邮件@GetMapping("/mail")//等同于@RequestMapping(method = RequestMethod.GET)public String sendmail(){service.sendmail("lulc@","182305213@","lulc@","会议通知","请于下午三点在1号会议室参加民主生活会");return "邮件发送成功!";}//多附件有邮件@GetMapping("/mailfile")public String sendfilemail(){File[] files =new File[2];//表明有两个附件files[0] =new File("D:\\会议内容.docx");//附件分别存放在D盘根目录files[1] =new File("D:\\会议议程.xlsx");service.sendfilemail("lulc@","182305213@","lulc@","会议通知","请于下午三点在1号会议室参加民主生活会,详见附件",files);return"带附件邮件发送成功!";}//thymeleaf模板作为正文的邮件@AutowiredTemplateEngine templateEngine;//注入TemplateEngine对网页模板进行渲染@GetMapping("/mailthy")public String sendthymail(){Context context =new Context();context.setVariable("username","路路");context.setVariable("gender","男");String htmlcontent =templateEngine.process("mailtemplate.html",context);File[] files =new File[2];//表明有两个附件files[0] =new File("D:\\内容预览.docx");//附件分别存放在D盘根目录files[1] =new File("D:\\使用手册.xlsx");service.sendthymeleafmail("lulc@","182305213@","lulc@","邮箱激活通知",htmlcontent,files);return"Thymeleaf邮件发送成功!";}}

4、右键DemomailApplication,点击Run DemomailApplication,运行程序。打开浏览器输入网址开始测试:http://localhost:8081/mailthy

Thymeleaf邮件发送成功!并将"username","路路","gender","男"动态赋值到邮件内容中。

6、总结

以上三种邮件发送方式基本上能满足大部分的业务需求,后续可以根据实际需求自行部署邮件发送服务,可使用网页、微信小程序、各式APP作为前端调用邮件发送服务,也可将其作为接口,供其他生产系统访问调用,并最终完成邮件发送业务。

最后补充一点:批量单用户发送邮件只需要循环收件人地址,调用邮件发送服务即可。

好了,本讲到此结束,后续我将陆续更新一些如何利用Spring-boot搭建生产级应用的案例,欢迎关注、留言、转发。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。