前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot 发送邮件

SpringBoot 发送邮件

作者头像
喜欢天文的pony站长
发布2020-06-29 11:58:19
4170
发布2020-06-29 11:58:19
举报
文章被收录于专栏:RabbitMQ实战

# 依赖

代码语言:javascript
复制
compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'

# 配置

代码语言:javascript
复制
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

# 发送简单文本邮件

代码语言:javascript
复制
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邮件

代码语言:javascript
复制
/**
     * 发送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
        }
    }

# 使用邮件模板发送邮件

  • 添加依赖
代码语言:javascript
复制
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
  • 配置
代码语言:javascript
复制
spring:
    thymeleaf:
    cache: true
    prefix:classpath: /templates/
    mode: HTML
  • 新建html模板文件
代码语言:javascript
复制
<!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>
代码语言:javascript
复制
/**
     * 使用邮件模板发送邮件
     */
    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
        }
    }

# 测试:

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

周末愉快~

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-10-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 喜欢天文 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • # 依赖
  • # 配置
  • # 发送简单文本邮件
  • # 发送html邮件
  • # 使用邮件模板发送邮件
  • # 测试:
相关产品与服务
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档