在很多服务中我经常需要用到发送邮件功能,所幸的是SpringBoot可以快速使用的框架 spring-boot-starter-mail
,只要引入改框架我们可以快速的完成发送邮件功能。
mail
Jar <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
在国内用的最多的就是QQ邮件和网易163邮件,这里会简单讲解获取两家服务商的发送邮件配置。
等录QQ邮箱,点击 设置
然后选择 账户
在下方可以看到 POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
,然后我们需要把 smtp
服务开启,开启成功后会得到一个秘钥。如图所示:
开启成功需要在 application.properties
配置文件中加入相应的配置,以下信息部分需要替换为自己的信息,教程结束下面的账号就会被停用
spring.mail.host=smtp.qq.com spring.mail.username=6928700@qq.com # 替换为自己的QQ邮箱号 spring.mail.password=owqpkjmqiasnbigc # 替换为自己的秘钥或授权码 spring.mail.port=465 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true # sender email.sender=6928700@qq.com # 替换为自己的QQ邮箱号
登录账户然后在 设置
找到 POP3/SMTP/IMAP
选项,然后开启smtp服务,具体操作如下图所示,然后修改对应的配置文件
spring.mail.host=smtp.163.com spring.mail.username=xmsjgzs@163.com # 替换为自己的163邮箱号 spring.mail.password=owqpkj163MC # 替换为自己的授权码 spring.mail.port=465 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true # sender email.sender=xmsjgzs@163.com # 替换为自己的163邮箱号
这里发送邮件我们主要用到的是 JavaMailSender
对象,发送简单邮件主要是发送字符串内容,复杂的邮件我们可能会添加附件或者是发送HTML格式的邮件,我们先测试简单的发送,代码如下:
override fun sendSimple(receiver: String, title: String, content: String) { logger.info("发送简单邮件服务") val message = mailSender.createMimeMessage() val helper = MimeMessageHelper(message, true) helper.setFrom(sender) helper.setTo(receiver) helper.setSubject(title) helper.setText(content) mailSender.send(message) }
测试代码
@RunWith(SpringJUnit4ClassRunner::class) @SpringBootTest class MailServiceImplTest { @Autowired lateinit var mailService: MailService @Test fun sendSimple() { mailService.sendSimple("xmsjgzs@163.com", "Hello Kotlin Mail", "SpringBoot Kotlin 专栏学习之JavaMailSender发送邮件") } }
检查邮件是否收到发送的内容
我们这里用的HTML模板引擎是 thymeleaf
,大家需要引入一下 spring-boot-starter-thymeleaf
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
有个地方需要注意,SpringBoot项目默认静态资源都是放在 resources/templates
目录下,所以我们编写的HTML模板就需要放在该目录下,具体内容如下:
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title th:text="${title}">Title</title> </head> <body> <h1 th:text="${name}">Demo</h1> <h1 th:text="${phone}">xxx</h1> </body> </html>
发送模板邮件主要实现代码
override fun sendMail(receiver: String, title: String, o: Any, templateName: String) { logger.info("开始发送邮件服务,To:{}", receiver) val message = mailSender.createMimeMessage() val helper = MimeMessageHelper(message, true) helper.setFrom(sender) helper.setTo(receiver) helper.setSubject(title) val context = Context() context.setVariable("title", title) /* * 设置动态数据,这里不建议强转,具体业务需求传入具体的对象 */ context.setVariables(o as MutableMap<String, Any>?) /* * 读取取模板html代码并赋值 */ val content = templateEngine.process(templateName, context) helper.setText(content, true) mailSender.send(message) logger.info("邮件发送结束") }
测试代码
@Test fun sendMail() { val model = HashMap<String, Any>() model["name"] = "Tom" model["phone"] = "69288888" mailService.sendMail("xmsjgzs@163.com", "Kotlin Template Mail", model, "mail") }
查看邮件我们可以看到如下内容:
附件的添加也是非常容易的,我需要先把发送的附件放在 resources/templates
目录下,然后在 MimeMessageHelper
对象中设置相应的属性即可,如下所示:
helper.addAttachment("test.txt", FileSystemResource(File("test.txt")))
package io.intodream.kotlin06.service.impl import io.intodream.kotlin06.service.MailService import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.core.io.FileSystemResource import org.springframework.mail.javamail.JavaMailSender import org.springframework.mail.javamail.MimeMessageHelper import org.springframework.stereotype.Service import org.thymeleaf.TemplateEngine import org.thymeleaf.context.Context import java.io.File /** * {描述} * * @author yangxianxi@gogpay.cn * @date 2019/4/8 19:19 * */ @Service class MailServiceImpl @Autowired constructor(private var mailSender: JavaMailSender, private var templateEngine: TemplateEngine) : MailService{ val logger : Logger = LoggerFactory.getLogger(MailServiceImpl::class.java) @Value("/${email.sender}") val sender: String = "6928700@qq.com" override fun sendSimple(receiver: String, title: String, content: String) { logger.info("发送简单邮件服务") val message = mailSender.createMimeMessage() val helper = MimeMessageHelper(message, true) helper.setFrom(sender) helper.setTo(receiver) helper.setSubject(title) helper.setText(content) mailSender.send(message) } override fun sendMail(receiver: String, title: String, o: Any, templateName: String) { logger.info("开始发送邮件服务,To:{}", receiver) val message = mailSender.createMimeMessage() val helper = MimeMessageHelper(message, true) helper.setFrom(sender) helper.setTo(receiver) helper.setSubject(title) val context = Context() context.setVariable("title", title) /* * 设置动态数据,这里不建议强转,具体业务需求传入具体的对象 */ context.setVariables(o as MutableMap<String, Any>?) /* * 添加附件 */ helper.addAttachment("test.txt", FileSystemResource(File("test.txt"))) /* * 读取取模板html代码并赋值 */ val content = templateEngine.process(templateName, context) helper.setText(content, true) mailSender.send(message) logger.info("邮件发送结束") } }
package io.intodream.kotlin06.service.impl import io.intodream.kotlin06.service.MailService import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringJUnit4ClassRunner /** * {描述} * * @author yangxianxi@gogpay.cn * @date 2019/4/9 18:38 */ @RunWith(SpringJUnit4ClassRunner::class) @SpringBootTest class MailServiceImplTest { @Autowired lateinit var mailService: MailService @Test fun sendSimple() { mailService.sendSimple("xmsjgzs@163.com", "Hello Kotlin Mail", "SpringBoot Kotlin 专栏学习之JavaMailSender发送邮件") } @Test fun sendMail() { val model = HashMap<String, Any>() model["name"] = "Tom" model["phone"] = "69288888" mailService.sendMail("xmsjgzs@163.com", "Kotlin Template Mail", model, "mail") } }
关于Kotlin使用 JavaMailSender
发送邮件的介绍就到此结束了,如果大家觉得教程有用麻烦点一下赞,如果有错误的地方欢迎指出。