SpringBoot 2.X Kotlin系列之JavaMailSender发送邮件

image

在很多服务中我经常需要用到发送邮件功能,所幸的是SpringBoot可以快速使用的框架spring-boot-starter-mail,只要引入改框架我们可以快速的完成发送邮件功能。

引入mailJar

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

获取邮件发送服务器配置

在国内用的最多的就是QQ邮件和网易163邮件,这里会简单讲解获取两家服务商的发送邮件配置。

QQ邮箱

等录QQ邮箱,点击设置然后选择账户在下方可以看到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,然后我们需要把smtp服务开启,开启成功后会得到一个秘钥。如图所示:

image

image

开启成功需要在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邮箱号

163邮箱

登录账户然后在设置找到POP3/SMTP/IMAP选项,然后开启smtp服务,具体操作如下图所示,然后修改对应的配置文件

image

image

image
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发送邮件")
    }

}

检查邮件是否收到发送的内容


image

发送模板邮件

我们这里用的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")
}

查看邮件我们可以看到如下内容:


image

邮件添加附件

附件的添加也是非常容易的,我需要先把发送的附件放在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发送邮件的介绍就到此结束了,如果大家觉得教程有用麻烦点一下赞,如果有错误的地方欢迎指出。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353