您的位置:首页 > 编程语言 > Java开发

SpringBoot 发送邮件

2018-10-19 21:46 357 查看

钉钉、微博极速扩容黑科技,点击观看阿里云弹性计算年度发布会!>>>

# 依赖

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

# 配置

  1. spring:

  2.    # 发邮件

  3.  mail:

  4.    host: smtp.qq.com

  5.    port: 587

  6.    username: 1185172056@qq.com

  7.    password: 不是qq邮箱的密码,是授权码

  8.    properties:

  9.      smtp:

  10.        auth: true

  11.        starttls:

  12.          enable: true

  13.          required: true

  14. #      mail:

  15. #        smtp:

  16. #          ssl:

  17. #            enable: true

# 发送简单文本邮件

  1. package com.futao.springmvcdemo.service.impl

  2. import com.alibaba.fastjson.JSO 2000 N

  3. import com.futao.springmvcdemo.model.system.MailM

  4. import com.futao.springmvcdemo.model.system.SystemConfig

  5. import com.futao.springmvcdemo.service.MailService

  6. import org.apache.rocketmq.client.producer.DefaultMQProducer

  7. import org.apache.rocketmq.common.message.Message

  8. import org.slf4j.LoggerFactory

  9. import org.springframework.beans.factory.annotation.Value

  10. import org.springframework.mail.SimpleMailMessage

  11. import org.springframework.mail.javamail.JavaMailSender

  12. import org.springframework.mail.javamail.MimeMessageHelper

  13. import org.springframework.stereotype.Service

  14. import org.thymeleaf.TemplateEngine

  15. import org.thymeleaf.context.Context

  16. import java.nio.charset.Charset

  17. import javax.annotation.Resource

  18. /**

  19. * @author futao

  20. * Created on 2018/10/17.

  21. */

  22. @Service

  23. open class MailServiceImpl : MailService {

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

  25.    @Value("\${spring.mail.username}")

  26.    lateinit var username: String

  27.    @Resource

  28.    lateinit var sender: JavaMailSender

  29.     /**

  30.     * 发送简单邮件

  31.     */

  32.    override fun sendSimpleEmail(to: Array<String>, cc: Array<String>, subject: String, content: String): Boolean {

  33.        return try {

  34.            val mailMessage = SimpleMailMessage().apply {

  35.                from = username

  36.                setTo(*to)

  37.                setCc(*cc)

  38.                setSubject(subject)

  39.                text = content

  40.            }

  41.            sender.send(mailMessage)

  42.            true

  43.        } catch (e: Exception) {

  44.            logger.error(e.message, e)

  45.            false

  46.        }

  47.    }

# 发送html邮件

  1. /**

  2.     * 发送html邮件

  3.     */

  4.    override fun sendHtmlEmail(to: Array<String>, cc: Array<String>, subject: String, content: String, isHtml: Boolean): Boolean {

  5.        return try {

  6.            val message = sender.createMimeMessage()

  7.            MimeMessageHelper(message).apply {

  8.                setFrom(username)

  9.                setTo(to)

  10.                setCc(cc)

  11.                setSubject(subject)

  12.                setText(content, isHtml)

  13.            }

  14.            sender.send(message)

  15.            true

  16. 2000
  17.        } catch (e: Exception) {

  18.            logger.error(e.message, e)

  19.            false

  20.        }

  21.    }

# 使用邮件模板发送邮件

  • 添加依赖

  1. compile('org.springframework.boot:spring-boot-starter-thymeleaf')

  • 配置

  1. spring:

  2.    thymeleaf:

  3.    cache: true

  4.    prefix:classpath: /templates/

  5.    mode: HTML

  • 新建html模板文件

  1. <!DOCTYPE html>

  2. <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

  3. <head>

  4.    <title>Email</title>

  5.    <meta charset="utf-8"/>

  6.    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>

  7.    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"

  8.          th:href="@{https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css}"/>

  9. </head>

  10. <style type="text/css">

  11.    .full-screen {

  12.        height: fit-content;

  13.        width: fit-content;

  14.    }

  15.    .fixed-page {

  16.        overflow-x: scroll;

  17.        overflow-y: scroll;

  18.    }

  19.    .container {

  20.        width: 100%;

  21.        padding-right: 15px;

  22.        padding-left: 15px;

  23.        margin-right: auto;

  24.        margin-left: auto

  25.    }

  26.    .jumbotron {

  27.        padding: 2rem 1rem;

  28.        margin-bottom: 2rem;

  29.        background-color: #e9ecef;

  30.        border-radius: .3rem

  31.    }

  32.    .jumbotron-fluid {

  33.        padding-right: 0;

  34.        padding-left: 0;

  35.        border-radius: 0

  36.    }

  37. </style>

  38. <body class="fixed-page">

  39. <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#ffffff"

  40.       style="font-family:'Microsoft YaHei';">

  41.    <div class="jumbotron jumbotron-fluid full-screen">

  42.        <div class="container  full-screen">

  43. 1000            <h3>Hi,

  44.                <span th:text="${username}">Developer</span>

  45.            </h3>

  46.            <p>There is an exception occurred in method

  47.                <code style="color: #d57e13;"><span th:text="${methodName}">methodName</span></code>,

  48.                the error message is :

  49.            </p>

  50.            <div>

  51.            <pre>

  52.                <code style="font-family: 'Source Code Pro';">

  53.                    <span th:text="${errorMessage}">Error Message</span>

  54.                </code>

  55.            </pre>

  56.            </div>

  57.            <span th:text="${occurredTime}">occurredTime</span>

  58.        </div>

  59.    </div>

  60. </table>

  61. </body>

  62. </html>

  1. /**

  2.     * 使用邮件模板发送邮件

  3.     */

  4.    override fun sendHtmlEmailWithTemplate(to: Array<String>, cc: Array<String>, subject: String, templatePath: String, context: Context): Boolean {

  5.        return try {

  6.            val message = sender.createMimeMessage()

  7.            MimeMessageHelper(message).apply {

  8.                setFrom(username)

  9.                setTo(to)

  10.                setCc(cc)

  11.                setSubject(subject)

  12.                setText(template.process(templatePath, context), true)

  13.            }

  14.            sender.send(message)

  15.            true

  16.        } catch (e: Exception) {

  17.            logger.error(e.message, e)

  18.            false

  19.        }

  20.    }

# 测试:

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


周末愉快~

本文分享自微信公众号 - 喜欢天文(AllUnderControl)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring boot