SpringBoot 发送邮件

依赖

compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'

配置

spring:
    # 发邮件
  mail:
    host: smtp.qq.com
    port: 587
    username: 1185172056@qq.com
    password: 不是qq邮箱的密码,是授权码
    properties:
      smtp:
        auth: true
        starttls:
          enable: true
          required: true
#      mail:
#        smtp:
#          ssl:
#            enable: true

发送简单文本邮件

package com.futao.springmvcdemo.service.impl

import com.alibaba.fastjson.JSON
import com.futao.springmvcdemo.model.system.MailM
import com.futao.springmvcdemo.model.system.SystemConfig
import com.futao.springmvcdemo.service.MailService
import org.apache.rocketmq.client.producer.DefaultMQProducer
import org.apache.rocketmq.common.message.Message
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.mail.SimpleMailMessage
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.nio.charset.Charset
import javax.annotation.Resource

/**
 * @author futao
 * Created on 2018/10/17.
 */
@Service
open class MailServiceImpl : MailService {

 private val logger = LoggerFactory.getLogger(MailServiceImpl::class.java)

    @Value("\${spring.mail.username}")
    lateinit var username: String

    @Resource
    lateinit var sender: JavaMailSender
     /**
     * 发送简单邮件
     */
    override fun sendSimpleEmail(to: Array<String>, cc: Array<String>, subject: String, content: String): Boolean {
        return try {
            val mailMessage = SimpleMailMessage().apply {
                from = username
                setTo(*to)
                setCc(*cc)
                setSubject(subject)
                text = content
            }
            sender.send(mailMessage)
            true
        } catch (e: Exception) {
            logger.error(e.message, e)
            false
        }
    }

发送html邮件

 /**
     * 发送html邮件
     */
    override fun sendHtmlEmail(to: Array<String>, cc: Array<String>, subject: String, content: String, isHtml: Boolean): Boolean {
        return try {
            val message = sender.createMimeMessage()
            MimeMessageHelper(message).apply {
                setFrom(username)
                setTo(to)
                setCc(cc)
                setSubject(subject)
                setText(content, isHtml)
            }
            sender.send(message)
            true
        } catch (e: Exception) {
            logger.error(e.message, e)
            false
        }
    }

使用邮件模板发送邮件

  • 添加依赖
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
  • 配置
spring:
    thymeleaf:
    cache: true
    prefix:classpath: /templates/
    mode: HTML
  • 新建html模板文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>Email</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
          th:href="@{https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css}"/>
</head>
<style type="text/css">
    .full-screen {
        height: fit-content;
        width: fit-content;
    }

    .fixed-page {
        overflow-x: scroll;
        overflow-y: scroll;
    }

    .container {
        width: 100%;
        padding-right: 15px;
        padding-left: 15px;
        margin-right: auto;
        margin-left: auto
    }

    .jumbotron {
        padding: 2rem 1rem;
        margin-bottom: 2rem;
        background-color: #e9ecef;
        border-radius: .3rem
    }

    .jumbotron-fluid {
        padding-right: 0;
        padding-left: 0;
        border-radius: 0
    }

</style>
<body class="fixed-page">
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#ffffff"
       style="font-family:'Microsoft YaHei';">
    <div class="jumbotron jumbotron-fluid full-screen">
        <div class="container  full-screen">
            <h3>Hi,
                <span th:text="${username}">Developer</span>
            </h3>
            <p>There is an exception occurred in method
                <code style="color: #d57e13;"><span th:text="${methodName}">methodName</span></code>,
                the error message is :
            </p>
            <div>
            <pre>
                <code style="font-family: 'Source Code Pro';">
                    <span th:text="${errorMessage}">Error Message</span>
                </code>
            </pre>
            </div>
            <span th:text="${occurredTime}">occurredTime</span>
        </div>
    </div>
</table>
</body>
</html>
/**
     * 使用邮件模板发送邮件
     */
    override fun sendHtmlEmailWithTemplate(to: Array<String>, cc: Array<String>, subject: String, templatePath: String, context: Context): Boolean {
        return try {
            val message = sender.createMimeMessage()
            MimeMessageHelper(message).apply {
                setFrom(username)
                setTo(to)
                setCc(cc)
                setSubject(subject)
                setText(template.process(templatePath, context), true)
            }
            sender.send(message)
            true
        } catch (e: Exception) {
            logger.error(e.message, e)
            false
        }
    }

测试:

SpringBoot 发送邮件
SpringBoot 发送邮件

下一篇文章将介绍使用消息队列发送邮件

上一篇:springboot整合druid连接池


下一篇:Springboot整合redis从安装到FLUSHALL