spring boot 集成邮件发送功能

2024-01-10 05:55:51

一、首先到QQ邮箱申请开启POP3、SMTP协议
在这里插入图片描述
二、安装依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.23</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

三、配置文件

spring:
  #配置邮箱发送邮件
  mail:
    default-encoding: utf-8 #默认编码
    host: smtp.qq.com #配置SMTP 服务器地址
    username: xxxxxxx@qq.com #发送者邮箱
    password: xxxxxxxxxxx#申请到的授权码
    port: 587 #端口号587或 465
    properties: #配置SSL 加密工厂
      mail:
        smtp:
          socketFactoryClass: javax.net.ssl.SSLSocketFactory
        debug: true #表示开启debug模式,这样,邮件发送的过程会在控制台打印出来,这样方便排查错误
        #配置这些好后,springboot会自动帮我们配置好相关的邮件发送类
  thymeleaf:
    cache: false
    prefix: classpath:/templates/

四、如果需要发送模板的邮件,则在/templates/目录下建立email.html文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>使用Thymeleaf作为邮件的模板</title>
</head>
<body>
<p>hello 欢迎加入 xxx 大家庭,您的入职信息如下:</p>
<table border="1">
    <tr>
        <td>姓名</td>
        <td th:text="${username}"></td>
    </tr>
    <tr>
        <td>职位</td>
        <td th:text="${position}"></td>
    </tr>
    <tr>
        <td>薪水</td>
        <td th:text="${salary}"></td>
    </tr>
</table>
<div style="color: #ff1a0e">一起努力创造辉煌</div>

</body>
</html>

五、如果需要异常打印信息的话新建自定义异常类BusinessException

public class BusinessException extends RuntimeException {
    public BusinessException(String msg){
        super(msg);
    }
}

六、如果需要发送附件的话,则新建网络文件转流类

package com.example.answer_system.utils;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

//文件转换工具
public class FileUtils {

    /**
     * 将网络文件转换为文件流
     * @param imageUrl
     * @return
     */
    public static MultipartFile fileUrlConvertToMultipartFile(String imageUrl) {
        try {
            // 将在线图片地址转换为URL对象
            URL url = new URL(imageUrl);
            // 打开URL连接
            URLConnection connection = url.openConnection();
            // 转换为HttpURLConnection对象
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            // 获取输入流
            InputStream inputStream = httpURLConnection.getInputStream();
            // 读取输入流中的数据,并保存到字节数组中
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            // 将字节数组转换为字节数组
            byte[] bytes = byteArrayOutputStream.toByteArray();
            // 创建ByteArrayInputStream对象,将字节数组传递给它
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            // 创建MultipartFile对象,将ByteArrayInputStream对象作为构造函数的参数
            MultipartFile multipartFile = new MockMultipartFile("file", "filename.jpg", "image/jpg", byteArrayInputStream);
            return multipartFile;
        }catch (IOException ex){
            ex.printStackTrace();
            throw new BusinessException("附件无效");
        }
    }
}

七、测试方法

package com.example.answer_system.service.impl;

import com.example.answer_system.service.IMailService;
import com.example.answer_system.utils.BusinessException;
import com.example.answer_system.utils.FileUtils;
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 javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Service
public class MailServiceImpl implements IMailService {
    @Resource
    public JavaMailSender javaMailSender;

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

    @Resource
    private TemplateEngine templateEngine;

    //简单文本
    @Override
    public String sendMailQQMsg(){
        SimpleMailMessage message=new SimpleMailMessage();//构建一个邮件对象
        message.setSubject("使用springboot发送邮件测试");//设置邮件主题
        message.setFrom(sendUserMailName);//设置邮件发送人,要与application.yml文件配置一致
        message.setTo(sendUserMailName);//设置收件人,如果有多个接收人,使用","隔开
        //message.setCc("3121624188@qq.com");//设置抄送人,可以有多个
        //message.setBcc("3121624188@qq.com");//设置隐秘抄送人,可以有多个
        message.setSentDate(new Date());//设置发送日期
        message.setText("小程使用springboot发送邮件的简单测试!!");//设置邮件正文
        javaMailSender.send(message);//发送邮件
        return "OK";
    }

    @Override
    public String sendAttachFileMail(String filePath) {

        try {
            MimeMessage mimeMessage=javaMailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(mimeMessage,true);//true表示构建一个带附件的邮件对象
            helper.setSubject("这是一封测试邮件,带附件的");
            helper.setFrom(sendUserMailName);
            helper.setTo(new String[]{sendUserMailName});
            helper.setSentDate(new Date());
            helper.setText("小程使用springboot发送可以带附件的邮件 测试!!");
            helper.addAttachment("james.jpg", FileUtils.fileUrlConvertToMultipartFile(filePath));//第一个参数是自定义的名称,第二个参数是文件的位置
            javaMailSender.send(mimeMessage);
        }catch (MessagingException ex){
            throw new BusinessException("发送异常");
        }catch (Exception ex){
            ex.printStackTrace();
        }

        finally {
            return "OK";
        }
    }

    @Override
    public String sendThymeleaf(){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject("使用Thymeleaf模板作为发送邮件的模板");
            helper.setFrom(sendUserMailName);
            helper.setTo(sendUserMailName);
            helper.setSentDate(new Date());
            //这里进入的是Template的Context
            Context context = new Context();
            //设置模板中的变量
            context.setVariable("username","程婷");
            context.setVariable("position","java开发工程师");
            context.setVariable("salary","XXXXXK");
            //第一个参数作为模板的,名称
            String process = templateEngine.process("email.html", context);
            //第二个参数true表示这是html文本
            helper.setText(process,true);
            javaMailSender.send(mimeMessage);
        }catch (MessagingException ex){
            throw new BusinessException("失败");
        }
        return "OK";
    }

}

文章来源:https://blog.csdn.net/weixin_41463944/article/details/135433223
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。