资讯专栏INFORMATION COLUMN

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

derek_334892 / 3250人阅读

摘要:在很多服务中我经常需要用到发送邮件功能,所幸的是可以快速使用的框架,只要引入改框架我们可以快速的完成发送邮件功能。引入获取邮件发送服务器配置在国内用的最多的就是邮件和网易邮件,这里会简单讲解获取两家服务商的发送邮件配置。

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

    org.springframework.boot
    spring-boot-starter-mail
获取邮件发送服务器配置

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

QQ邮箱

等录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邮箱号
163邮箱

登录账户然后在设置找到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


    org.springframework.boot
    spring-boot-starter-thymeleaf

有个地方需要注意,SpringBoot项目默认静态资源都是放在resources/templates目录下,所以我们编写的HTML模板就需要放在该目录下,具体内容如下:




    
    Title


    

Demo

xxx

发送模板邮件主要实现代码

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?)
    /*
     * 读取取模板html代码并赋值
     */
    val content = templateEngine.process(templateName, context)
    helper.setText(content, true)

    mailSender.send(message)
    logger.info("邮件发送结束")
}

测试代码

@Test
fun sendMail() {
    val model = HashMap()
    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?)
        /*
         * 添加附件
         */
        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()
        model["name"] = "Tom"
        model["phone"] = "69288888"
        mailService.sendMail("xmsjgzs@163.com", "Kotlin Template Mail", model, "mail")
    }
}

关于Kotlin使用JavaMailSender发送邮件的介绍就到此结束了,如果大家觉得教程有用麻烦点一下赞,如果有错误的地方欢迎指出。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/74106.html

相关文章

  • Spring Boot 2.x (十八):邮件服务一文打尽

    摘要:前景介绍在日常的工作中,我们经常会用到邮件服务,比如发送验证码,找回密码确认,注册时邮件验证等,所以今天在这里进行邮件服务的一些操作。 前景介绍 在日常的工作中,我们经常会用到邮件服务,比如发送验证码,找回密码确认,注册时邮件验证等,所以今天在这里进行邮件服务的一些操作。 大致思路 我们要做的其实就是把Java程序作为一个客户端,然后通过配置SMTP协议去连接我们所使用的发送邮箱(fr...

    idealcn 评论0 收藏0
  • SpringBoot 2.X Kotlin系列RestTemplate配置及使用

    摘要:调用的默认构造函数,对象在底层通过使用包下的实现创建请求,可以通过使用指定不同的请求方式。接口主要提供了两种实现方式一种是,使用提供的方式既包提供的方式创建底层的请求连接。 showImg(http://download.qfeoo.com/kotlin_springboot_logo.png); 自从RESTFul API兴起后,Spring就给开发者提供了一个访问Rest的客服端,...

    wdzgege 评论0 收藏0
  • SpringBoot 2.X Kotlin 系列Hello World

    摘要:二教程环境三创建项目创建项目有两种方式一种是在官网上创建二是在上创建如图所示勾选然后点,然后一直默认最后点击完成即可。我们这里看到和普通的接口没有异同,除了返回类型是用包装之外。与之对应的还有,这个后面我们会讲到。 showImg(https://segmentfault.com/img/remote/1460000018819338?w=1024&h=500); 从去年开始就开始学习...

    warkiz 评论0 收藏0
  • 结合Spring发送邮件的四种正确姿势,你知道几种?

    摘要:我拿网易邮箱账号举例子,那么我们如何才能让你的邮箱账号可以利用第三方发送邮件这里的第三方就是我们即将编写的程序。 一 前言 测试所使用的环境 测试使用的环境是企业主流的SSM 框架即 SpringMVC+Spring+Mybatis。为了节省时间,我直接使用的是我上次的SSM项目中整合Echarts开发该项目已经搭建完成的SSM环境。 标题说的四种姿势指的是哪四种姿势? 发送text...

    doodlewind 评论0 收藏0
  • Spring Boot 邮件发送的 5 种姿势!

    摘要:也就是说用户先将邮件投递到腾讯的服务器这个过程就使用了协议,然后腾讯的服务器将邮件投递到网易的服务器这个过程也依然使用了协议,服务器就是用来收邮件。 邮件发送其实是一个非常常见的需求,用户注册,找回密码等地方,都会用到,使用 JavaSE 代码发送邮件,步骤还是挺繁琐的,Spring Boot 中对于邮件发送,提供了相关的自动化配置类,使得邮件发送变得非常容易,本文我们就来一探究竟!看...

    W4n9Hu1 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<