SpringBoot学习历程(十一):SpringBoot2.X集成mail发送邮件

前言

  • 本人github仓库地址:https://github.com/RabbitsInTheGrass/springBoot-Learning
  • 暂时使用的是Spring提供的org.springframework.mail.javamail.JavaMailSender发送邮件。

1. 引入依赖

<!--引入邮件依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--引入Thymeleaf依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. 设置邮件配置信息

spring:
  #发送邮件设置
  mail:
    host: smtp.163.com
    username: xxxxxx@163.com
    #对l63邮箱,password是授权码
    password: xxxxxx
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

注意:如果发送方用的是163邮箱,password对应的是邮箱的授权码,而不是你的邮箱密码。

3. 发送邮件

3.1 发送普通文本邮件

EmailController .java

package com.rabbits.learn.controller;

import com.rabbits.learn.util.JmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;

import java.io.File;

/**
 * @Description: 发送邮件类
 * @Author: RabbitsInTheGrass_xj
 * @Date: 2019/10/2 09:39
 */
@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private JmsUtil jmsUtil;

    /**
     * 发送简单的邮件
     *
     * @return 发送结果
     */
    @RequestMapping("sendSimpleEmail")
    public String sendSimpleEmail() {
        SimpleMailMessage message = new SimpleMailMessage();
        // 接收地址
        message.setTo("2398937985@qq.com");
        // 标题
        message.setSubject("一封简单的邮件");
        // 内容
        message.setText("使用Spring Boot发送简单邮件。");
        return jmsUtil.sendSimpleEmail(message);
    }
 }

JmsUtil .java

package com.rabbits.learn.util;

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.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;

/**
 * @Description: 发送邮件工具类
 * @Author: RabbitsInTheGrass_xj
 * @Date: 2019/10/2 09:45
 */
@Component
public class JmsUtil {

    private static final Logger logger = LoggerFactory.getLogger(JmsUtil.class);

    @Autowired
    private JavaMailSender jms;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    public String sendSimpleEmail(SimpleMailMessage message) {
        try {
            message.setFrom(from);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "发送失败";
        }
    }
}

3.2 发送HTML格式内容的邮件

EmailController .java

    /**
     * 发送HTML格式内容的邮件
     * @return 发送结果
     */
    @RequestMapping("sendHtmlEmail")
    public String sendHtmlEmail() {
        // 接收地址
        String toAddress = "xxxxxxx@qq.com";
        // 标题
        String subject = "一封HTML格式内容的邮件";
        // 带HTML格式的内容
        StringBuilder sb = new StringBuilder("<p style='color:#42b983'>我要发送一份HTML格式内容的邮件。</p>");
        return jmsUtil.sendHtmlEmail(toAddress,subject,sb.toString());
    }

JmsUtil .java

    public String sendHtmlEmail(String toAddress, String subject, String text) {
        try {
            MimeMessage message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddress);
            helper.setSubject(subject);
            //true表示发送HTML格式邮件
            helper.setText(text, true);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "发送失败";
        }
    }

3.3 发送带附件的邮件

EmailController .java

    /**
     *发送带附件的邮件
     * @return 发送结果
     */
    @RequestMapping("sendAttachmentsMail")
    public String sendAttachmentsMail() {
        // 接收地址
        String toAddress = "xxxxx@qq.com";
        // 标题
        String subject = "一封带附件的邮件";
        // 内容
        String text = "详情参见附件内容!";
        // 传入附件
        FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/file/xxxx.doc"));
        return jmsUtil.sendAttachmentsMail(toAddress,subject,text,file);
    }

JmsUtil .java

    public String sendAttachmentsMail(String toAddress, String subject, String text, FileSystemResource file) {
        try {
            MimeMessage message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddress);
            helper.setSubject(subject);
            helper.setText(text);
            helper.addAttachment(file.getFilename(), file);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "发送失败";
        }
    }

3.4 发送带静态资源的邮件

EmailController .java

    /**
     * 发送带静态资源的邮件
     * @return 发送结果
     */
    @RequestMapping("sendInlineMail")
    public String sendInlineMail() {
        // 接收地址
        String toAddress = "xxxxxxx@qq.com";
        // 标题
        String subject = "一封带静态资源的邮件";
        String contentId = "img";
        // 内容
        String text = "<html><body>一份美图:<img src='cid:" + contentId + "'/></body></html>";
        // 传入附件
        FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/yourName.jpg"));
        return jmsUtil.sendInlineMail(toAddress,subject,text,file,contentId);
    }

JmsUtil .java

    public String sendInlineMail(String toAddress, String subject, String text, FileSystemResource file, String contentId) {
        MimeMessage message;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddress);
            helper.setSubject(subject);
            helper.setText(text,true);
            //contentId 必须与图片标签里cid后的名称相对应,例如:img
            helper.addInline(contentId, file);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "发送失败";
        }
    }

3.5 使用模板发送邮件

在发送验证码等情况下可以创建一个邮件的模板,唯一的变量为验证码。这个例子中使用的模板解析引擎为Thymeleaf,所以必须引入Thymeleaf依赖。

EmailController .java

    /**
     * 发送模板邮件
     *
     * @param code 验证码
     * @return 发送结果
     */
    @RequestMapping("sendTemplateEmail")
    public String sendTemplateEmail(String code) {
        //接收地址
        String toAddress = "xxxxx@qq.com";
        //标题
        String subject = "发送一份模板邮件";
        //邮件模板
        String templateName = "emailTemplate";
        Context context = new Context();
        context.setVariable("code", code);
        return jmsUtil.sendInlineMail(toAddress, subject, templateName, context);

    }

JmsUtil .java

    public String sendInlineMail(String toAddress, String subject, String templateName, Context context) {
        try {
            MimeMessage message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            // 接收地址
            helper.setTo(toAddress);
            // 标题
            helper.setSubject(subject);
            // 处理邮件模板
            String template = templateEngine.process(templateName, context);
            helper.setText(template, true);
            jms.send(message);
            return "发送成功";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "发送失败";
        }
    }

emailTemplate.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>验证码邮件模板</title>
</head>
<body>
您好,您的验证码为<span th:text="${code}"></span>,请在两分钟内使用完成操作。
</body>
</html>

4. 启动服务验证

启动服务后请求各个方法即可。

  • 27
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RabbitsInTheGrass

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值