邮件服务是经常使用的服务之一,做用不少,对外能够给用户发送活动、营销广告等;对内能够发送系统监控报告与告警。html
本文将介绍Springboot如何整合邮件服务,并给出不一样邮件服务商的整合配置。java
如图所示: spring
Springboot的搭建很是简单,咱们使用 Spring Initializr来构建,十分方便,选择须要用到的模块,就能快速完成项目的搭建: app
为了使用邮件服务,咱们须要引入相关的依赖,对于Springboot加入下面的依赖便可:spring-boot
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
须要配置邮件服务提供商的相关参数,如服务地址、用户名及密码等。下面的例子是QQ的配置,其中密码并非QQ密码,而是QQ受权码,后续咱们再讲怎么得到。post
Springboot的配置文件application.yml
以下:测试
server: port: 8080 spring: profiles: active: qq --- spring: profiles: qq mail: host: smtp.qq.com username: xxx@qq.com password: xxx properties: mail: smtp: auth: true starttls: enable: true required: true --- spring: profiles: netEase mail: host: smtp.163.com username: xxx@163.com password: xxx properties: mail: smtp: auth: true starttls: enable: true required: true
将JavaMailSender注入,组装Message后,就能够发送最简单的文本邮件了。ui
@Autowired private JavaMailSender emailSender; public void sendNormalText(String from, String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(text); emailSender.send(message); }
服务调用实现后,经过Controller对外暴露REST接口,具体代码以下:3d
@Value("${spring.mail.username}") private String username; @Autowired private MailService mailService; @GetMapping("/normalText") public Mono<String> sendNormalText() { mailService.sendNormalText(username, username, "Springboot Mail(Normal Text)", "This is a mail from Springboot!"); return Mono.just("sent"); }
把实现的MailService
注入到Controller里,调用对应的方法便可。本次的邮件发送人和收件人都是同一个账户,实际实现能够灵活配置。code
经过Postman调用接口来测试一下能不能正常发送: 成功返回"sent",并收到了邮件,测试经过。
简单文本邮件如何发送,刚刚已经讲解,再也不赘述。
纯文本虽然已经能知足不少需求,但不少时候也须要更加丰富的样式来提升邮件的表现力。这时HTML类型的邮件就很是有用。
Service代码以下:
public void sendHtml(String from, String to, String subject, String text) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); emailSender.send(message); }
与简单的文本不一样的是,本次用到了MimeMessage
和MimeMessageHelper
,这是很是有用的类,后续咱们常常会用到,组合使用能大大丰富邮件表现形式。
Controller的代码以下:
@GetMapping("/html") public Mono<String> sendHtml() throws MessagingException { mailService.sendHtml(username, username, "Springboot Mail(HTML)", "<h1>This is a mail from Springboot!</h1>"); return Mono.just("sent"); }
邮件发送文件再正常不过,发送附件须要使用MimeMessageHelper.addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)
方法,第一个参数为附件名,第二参数为文件流资源。Service代码以下:
public void sendAttachment(String from, String to, String subject, String text, String filePath) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); FileSystemResource file = new FileSystemResource(new File(filePath)); helper.addAttachment(filePath, file); emailSender.send(message); }
Controller代码以下:
@GetMapping("/attachment") public Mono<String> sendAttachment() throws MessagingException { mailService.sendAttachment(username, username, "Springboot Mail(Attachment)", "<h1>Please check the attachment!</h1>", "/Pictures/postman.png"); return Mono.just("sent"); }
咱们访问的网页其实也是一个HTML,是能够带不少静态资源的,如图片、视频等。Service代码以下:
public void sendStaticResource(String from, String to, String subject, String text, String filePath, String contentId) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); FileSystemResource file = new FileSystemResource(new File(filePath)); helper.addInline(contentId, file); emailSender.send(message); }
其中,contentId
为HTML里静态资源的ID,须要对应好。
Controller代码以下:
@GetMapping("/inlinePicture") public Mono<String> sendStaticResource() throws MessagingException { mailService.sendStaticResource(username, username, "Springboot Mail(Static Resource)", "<html><body>With inline picture<img src='cid:picture' /></body></html>", "/Pictures/postman.png", "picture"); return Mono.just("sent"); }
Java的模板引擎不少,著名的有Freemarker、Thymeleaf、Velocity等,这不是本点的重点,因此只以Freemarker为例使用。
Service代码以下:
@Autowired private FreeMarkerConfigurer freeMarkerConfigurer; public void sendTemplateFreemarker(String from, String to, String subject, Map<String, Object> model, String templateFile) throws Exception { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateFile); String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); helper.setText(html, true); emailSender.send(message); }
注意须要注入FreeMarkerConfigurer
,而后使用FreeMarkerTemplateUtils
解析模板,返回String
,就能够做为内容发送了。
Controller代码以下:
@GetMapping("/template") public Mono<String> sendTemplateFreemarker() throws Exception { Map<String, Object> model = new HashMap<>(); model.put("username", username); model.put("templateType", "Freemarker"); mailService.sendTemplateFreemarker(username, username, "Springboot Mail(Template)", model, "template.html"); return Mono.just("sent"); }
注意模板文件template.html
要放在**resources/templates/**目录下面,这样才能找获得。
模板内容以下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hello ${username}</h1> <h1>This is a mail from Springboot using ${templateType}</h1> </body> </html>
其中${username}
和${templateType}
为须要替换的变量名,Freemarker提供了不少丰富的变量表达式,这里不展开讲了。
邮件服务的提供商不少,国内最经常使用的应该是QQ邮箱和网易163邮箱了。
集成QQ邮件须要有必备的帐号,还要开通受权码。开通受权码后配置一下就可使用了,官方的文档以下:
须要注意的是,开通受权码是须要使用绑定的手机号发短信到特定号码的,若是没有绑定手机或者绑定手机不可用,那都会影响开通。
开通以后,受权码就要以做为密码配置到文件中。
网易的开通方式与QQ没有太大差异,具体的指导能够看以下官方文档:
一样也是须要绑定手机进行操做。
本次例子发送后收到邮件如图所示: 邮件功能强大,Springboot也很是容易整合。技术利器,善用而不滥用。
欢迎关注公众号**<南瓜慢说>**,将为你持续更新...
本文由博客一文多发平台 OpenWrite 发布!