springboot学习(二十九) 使用springboot发送邮件

下面记录使用springboot发送四种邮件的方法:普通文本、html、附件、模板html

1 引入springboot依赖包,这里使用gradle,使用maven请替换为对应的依赖就好

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

spring-boot-starter-mail实现邮件发送
spring-boot-starter-thymeleaf实现模板的创建

2 在resources/templates中创建一个模板html:emailTemplate.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>这是一个测试的模板</title>
</head>
<body>
您的账号存在异常,请点击下面链接进行安全验证<br/>
<a href="#" th:href="@{http://www.lalalala.com/{userid}(userid=${userid})}">安全验证</a>
</body>
</html>

3 四种邮件发送测试代码

package com.iscas.biz.test.controller;

import com.iscas.templet.common.BaseController;
import com.iscas.templet.common.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送测试
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2020/8/12 21:16
 * @since jdk1.8
 */
@RestController
@RequestMapping("/send/email/test")
@Slf4j
public class SendEmailController extends BaseController {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 测试发送普通文本邮件
     * */
    @GetMapping("/text")
    public ResponseEntity testText() {

        SimpleMailMessage message = new SimpleMailMessage();
        // 发件人地址
        message.setFrom("461402005@qq.com");
        // 收件人地址
        message.setTo("76775081@qq.com");
        // 邮件标题
        message.setSubject("这是一个测试");
        // 邮件正文
        message.setText("这是测试正文");

        javaMailSender.send(message);
        log.debug("发送成功!");

        return getResponse();
    }

    /**
     * 测试发送HTML邮件
     * */
    @GetMapping("/html")
    public ResponseEntity testHtml() throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom("461402005@qq.com");
        // 收件人地址
        helper.setTo("76775081@qq.com");
        helper.setSubject("这是html测试");
        // 发送HTML邮件
        String html = "<html><body><h1>这是测试测试</h1></body></html>";
        helper.setText(html, true);

        javaMailSender.send(message);
        log.debug("发送成功");

        return getResponse();
    }

    /**
     * 测试发送附件
     * */
    @GetMapping("/attachment")
    public ResponseEntity testAttachment() throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom("461402005@qq.com");
        // 收件人地址
        helper.setTo("76775081@qq.com");
        helper.setSubject("这是附件测试");
        // 发送HTML
        String html = "<html><body><h1>这是测试测试</h1></body></html>";
        helper.setText(html, true);

        //发送附件
        FileSystemResource file = new FileSystemResource("E:\\test\\repo1\\a.txt");
        // 发送文件名
        String fileName = file.getFilename();
        helper.addAttachment(fileName, file);

        javaMailSender.send(message);
        log.debug("发送成功");

        return getResponse();
    }

    /**
     * 测试发送thymeleaf模板邮件
     * */
    @GetMapping("/template")
    public ResponseEntity testTemplate() throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom("461402005@qq.com");
        // 收件人地址
        helper.setTo("76775081@qq.com");
        helper.setSubject("这是模板测试");

        //获取模板生成html
        Context context = new Context();
        // 这里的id与resources/templates下的模板文件中的${userid}必须对应
        context.setVariable("userid", 1);
        // 这里的"emailTemplate"与resources/templates下的模板文件一直
        String html = templateEngine.process("emailTemplate", context);
        helper.setText(html, true);

        //发送附件
        FileSystemResource file = new FileSystemResource("E:\\test\\repo1\\a.txt");
        // 发送文件名
        String fileName = file.getFilename();
        helper.addAttachment(fileName, file);

        javaMailSender.send(message);
        log.debug("发送成功");

        return getResponse();
    }
}

4 将邮件发送封装为工具类

package com.iscas.base.biz.service.common;

import cn.hutool.core.io.IoUtil;
import com.iscas.templet.common.ResponseEntity;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 发送邮件工具
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2020/8/12 21:52
 * @since jdk1.8
 */
@Service
@Slf4j
public class SendEmailService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送普通文本邮件
     *
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param content 邮件正文文本
     * */
    public void sendText(String from, String to, String title, String content) {


        SimpleMailMessage message = new SimpleMailMessage();
        // 发件人地址
        message.setFrom(from);
        // 收件人地址
        message.setTo(to);
        // 邮件标题
        message.setSubject(title);
        // 邮件正文
        message.setText(content);

        javaMailSender.send(message);
        log.debug("邮件发送成功!");
    }

    /**
     * 发送HTML邮件
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param html 邮件正文html
     * */
    public void sendHtml(String from, String to, String title, String html) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom(from);
        // 收件人地址
        helper.setTo(to);
        helper.setSubject(title);
        // 发送HTML邮件
        helper.setText(html, true);

        javaMailSender.send(message);
        log.debug("邮件发送成功");

    }

    /**
     * 发送附件
     *
     *
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param html 邮件正文html
     * @param inputStream 附件输入流
     * @param fileName 文件名称
     *
     * */
    public void sendAttachment(String from, String to, String title, String html, InputStream inputStream, String fileName) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom(from);
        // 收件人地址
        helper.setTo(to);
        helper.setSubject(title);
        // 发送HTML
        helper.setText(html, true);

        //发送附件

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IoUtil.copy(inputStream, baos);

        ByteArrayResource byteArrayResource = new ByteArrayResource(baos.toByteArray());
        // 发送文件名
        helper.addAttachment(fileName, byteArrayResource);

        javaMailSender.send(message);
        log.debug("发送成功");

    }

    /**
     * 测试发送thymeleaf模板邮件
     * templateName必须在resources/templates下
     *
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param templateName 模板名称,templateName必须在resources/templates下
     * @param context 构建模板的上下文,构建方式参见单元测试
     * */
    @GetMapping("/template")
    public void sendTemplate(String from, String to, String title, String templateName, Context context) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        // 这里与发送文本邮件有所不同
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 发件人地址
        helper.setFrom(from);
        // 收件人地址
        helper.setTo(to);
        helper.setSubject(title);

        //获取模板生成html
        String html = templateEngine.process(templateName, context);
        helper.setText(html, true);

        javaMailSender.send(message);
        log.debug("邮件发送成功");

    }

    /**
     * 测试发送thymeleaf模板邮件,并携带附件
     * templateName必须在resources/templates下
     * @version 1.0
     * @since jdk1.8
     * @date 2020/8/12
     * @param from 发送邮件地址
     * @param to 接收邮件地址
     * @param title 邮件主题
     * @param templateName 模板名称,templateName必须在resources/templates下
     * @param context 构建模板的上下文,构建方式参见单元测试
     * @param inputStream 附件输入流
     * @param fileName 文件名称
     * */
    public void sendTemplateWithAttachment(String from, String to, String title, String templateName, Context context, InputStream inputStream, String fileName) throws MessagingException {
        //获取模板生成html
        String html = templateEngine.process(templateName, context);
        sendAttachment(from, to, title, html, inputStream, fileName);
    }
}

5 单元测试

package com.iscas.biz.service;

import com.iscas.base.biz.service.common.SendEmailService;
import com.iscas.biz.BizApp;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 邮件发送测试
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2020/8/12 22:05
 * @since jdk1.8
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BizApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
public class SendEmailServiceTests {
    @Autowired
    private SendEmailService sendEmailService;
    /**
     * 测试发送普通文本邮件
     * */
    @Test
//    @Ignore
    public void testText() {
        sendEmailService.sendText("461402005@qq.com", "76775081@qq.com", "这是文本测试", "这是测试正文");
    }

    /**
     * 测试发送HTML邮件
     * */
    @Test
//    @Ignore
    public void testHtml() throws MessagingException {
        String html = "<html><body><h1>这是测试测试</h1></body></html>";
        sendEmailService.sendHtml("461402005@qq.com", "76775081@qq.com", "这是html测试", html);
    }

    /**
     * 测试发送附件
     * */
    @Test
//    @Ignore
    public void testAttachment() throws MessagingException, IOException {
        InputStream is = new FileInputStream("E:\\test\\repo1\\a.txt");
        String html = "<html><body><h1>这是测试测试</h1></body></html>";
        sendEmailService.sendAttachment("461402005@qq.com", "76775081@qq.com", "这是html测试", html, is, "测试.txt");

    }

    /**
     * 测试发送thymeleaf模板邮件
     * */
    @Test
//    @Ignore
    public void testTemplate() throws MessagingException {
        //获取模板生成html
        Context context = new Context();
        // 这里的id与resources/templates下的模板文件中的${userid}必须对应
        context.setVariable("userid", 1);
        // 这里的"emailTemplate"与resources/templates下的模板文件一直
        sendEmailService.sendTemplate("461402005@qq.com", "76775081@qq.com", "这是模板测试", "emailTemplate", context);

    }

    /**
     * 测试发送thymeleaf模板邮件,并携带附件
     * */
    @Test
//    @Ignore
    public void testTemplateWithAttachment() throws MessagingException, IOException {
        //获取模板生成html
        Context context = new Context();
        // 这里的id与resources/templates下的模板文件中的${userid}必须对应
        context.setVariable("userid", 1);
        // 这里的"emailTemplate"与resources/templates下的模板文件一致
        InputStream is = new FileInputStream("E:\\test\\repo1\\a.txt");
        sendEmailService.sendTemplateWithAttachment("461402005@qq.com", "76775081@qq.com", "这是模板测试", "emailTemplate", context, is, "测试测试测试.txt");

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值