spring boot发送邮件

文章目录

项目目录结构

添加maven依赖

xml 复制代码
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
	<version>2.7.10</version>
</dependency>

application.yml配置发信人信息

我这里已qq邮箱为例,如果是其它邮箱也一样,需要修改 host

password 是授权码,不是登录密码

邮箱设置开启服务,生成授权码

yml 复制代码
spring:
  mail:
    host: smtp.qq.com
    username: [发送邮箱账号]
    password: [邮箱授权码]
    default-encoding: UTF-8
    protocol: smtp
    port: 587
    properties:
      mail:
        stmp:
          ssl:
            enable: true

编码测试

创建 Email 工具类 EmailUtil

java 复制代码
package com.example.demoboot.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.MailSender;
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 java.io.File;
import java.io.IOException;
import java.util.Map;


@Component
public class EmailUtil {

    @Value("${spring.mail.username}")
    private String from; // 发件人
    private MailSender mailSender;
    private JavaMailSender javaMailSender;  // JavaMailSender 继承了 MailSender ,可以发送更复杂的邮件,可以携带附件。
    private TemplateEngine templateEngine;

    @Autowired
    public EmailUtil(MailSender mailSender, JavaMailSender javaMailSender, TemplateEngine templateEngine) {
        this.mailSender = mailSender;
        this.javaMailSender = javaMailSender;
        this.templateEngine = templateEngine;
    }

    /**
     * 发送一般邮件 -- 无附件
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     * @return 是否成功
     */
    public boolean sendGeneralEmail(String subject, String content, String[] to) {
        // 创建邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        // 设置收件人
        message.setTo(to);
        // 设置邮件主题
        message.setSubject(subject);
        // 设置邮件内容
        message.setText(content);
        // 发送邮件
        mailSender.send(message);
        return true;
    }

    /**
     * 发送带附件的邮件
     * @param to        收件人
     * @param subject   主题
     * @param content   内容
     * @param filePaths 附件路径
     * @return 是否成功
     */
    public boolean sendAttachmentsEmail(String subject, String content, String[] to, String[] filePaths) throws MessagingException, IOException {

        // 创建邮件消息
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        // 设置收件人
        helper.setTo(to);
        // 设置邮件主题
        helper.setSubject(subject);
        // 设置邮件内容
        helper.setText(content);

        // 添加附件
        if (filePaths != null) {
            for (String filePath : filePaths) {
                ClassPathResource resource = new ClassPathResource(filePath);
                String filename = resource.getFilename();
                File file = resource.getFile();
                assert filename != null;
                helper.addAttachment(filename, file);
            }
        }
        // 发送邮件
        javaMailSender.send(mimeMessage);
        return true;
    }

    /**
     * 发送带静态图片资源的邮件,图片资源内嵌在消息主题中
     * @param to         收件人
     * @param subject    主题
     * @param content    内容
     * @param picPathMap 静态资源路径
     * @return 是否成功
     */
    public boolean sendInlinePictureEmail(String subject, String content, String[] to, Map<String, String> picPathMap) throws MessagingException {
        // 创建邮件消息
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        // 设置发件人
        helper.setFrom(from);
        // 设置收件人
        helper.setTo(to);
        // 设置邮件主题
        helper.setSubject(subject);
        // html内容图片
        StringBuffer buffer = new StringBuffer();
        buffer.append("<html><body><div>");
        buffer.append(content);
        buffer.append("</div>包含以下图片:</br>");
        picPathMap.forEach((k, v) -> buffer.append("<img src=\'cid:")
                                           .append(k)
                                           .append("\'></br>"));
        buffer.append("</body></html>");
        helper.setText(buffer.toString(), true);
        // 指定讲资源地址
        picPathMap.forEach((k, v) -> {
            // FileSystemResource res = new FileSystemResource(new File(v));
            ClassPathResource res = new ClassPathResource(v);
            try {
                helper.addInline(k, res);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        });

        javaMailSender.send(mimeMessage);
        return true;
    }

	/**
     * 发送模板邮件
     * @param subject 主题
     * @param templateName  模板名称
     * @param templateData  模板参数
     * @param to    收件人
     * @return
     * @throws MessagingException
     */
    public boolean sendTemplateEmail(String subject, String templateName, Map<String, Object> templateData, String[] to) throws MessagingException {

        Context context = new Context();
        context.setVariables(templateData);
        String content = templateEngine.process(templateName, context);
        // 创建邮件消息
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        // 设置收件人
        helper.setTo(to);
        // 设置邮件主题
        helper.setSubject(subject);
        // 设置邮件内容
        helper.setText(content, true);
        // 发送邮件
        javaMailSender.send(mimeMessage);
        return true;
    }
}

测试发送邮件

java 复制代码
package com.example.demoboot.controller;

import com.example.demoboot.utils.EmailUtil;
import jakarta.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;

import java.io.IOException;
import java.util.HashMap;

@Controller
@RequestMapping("/mail")
public class MailController {

    private EmailUtil emailUtil;


    @Autowired
    public MailController(EmailUtil emailUtil) {
        this.emailUtil = emailUtil;
    }

    @ResponseBody
    @RequestMapping("/send/1")
    public String send() {
        emailUtil.sendGeneralEmail("测试邮件", "测试邮件内容", new String[]{"xxxxx@qq.com"});
        return "success";
    }

    @ResponseBody
    @RequestMapping("/send/2")
    public String send2() {
        HashMap<String, String> map = new HashMap<>();
        map.put("1", "static/1.jpg");
        map.put("2", "static/2.jpg");
        try {
            emailUtil.sendInlinePictureEmail("测试邮件", "测试邮件内容", new String[]{"xxxxx@qq.com"}, map);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        return "success";
    }

    @ResponseBody
    @RequestMapping("/send/3")
    public String send3() {
        try {
            emailUtil.sendAttachmentsEmail("测试邮件", "测试邮件内容", new String[]{"xxxxx@qq.com"}, new String[]{"static/1.jpg", "static/2.jpg"});
        } catch (MessagingException | IOException e) {
            throw new RuntimeException(e);
        }
        return "success";
    }

	@ResponseBody
    @RequestMapping("/send/4")
    public String send4() throws MessagingException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("info", "测试邮件");
        map.put("say", "你好!!!!!!!!");
        emailUtil.sendTemplateEmail("测试邮件", "mailTemplate", map, new String[]{"762741385@qq.com"});
        return "mailTemplate";
    }
}
相关推荐
极客先躯40 分钟前
高级java每日一道面试题-2024年10月3日-分布式篇-分布式系统中的容错策略都有哪些?
java·分布式·版本控制·共识算法·超时重试·心跳检测·容错策略
夜月行者1 小时前
如何使用ssm实现基于SSM的宠物服务平台的设计与实现+vue
java·后端·ssm
程序猿小D1 小时前
第二百六十七节 JPA教程 - JPA查询AND条件示例
java·开发语言·前端·数据库·windows·python·jpa
Yvemil71 小时前
RabbitMQ 入门到精通指南
开发语言·后端·ruby
sdg_advance1 小时前
Spring Cloud之OpenFeign的具体实践
后端·spring cloud·openfeign
潘多编程1 小时前
Java中的状态机实现:使用Spring State Machine管理复杂状态流转
java·开发语言·spring
_阿伟_2 小时前
SpringMVC
java·spring
代码在改了2 小时前
springboot厨房达人美食分享平台(源码+文档+调试+答疑)
java·spring boot
猿java2 小时前
使用 Kafka面临的挑战
java·后端·kafka
碳苯2 小时前
【rCore OS 开源操作系统】Rust 枚举与模式匹配
开发语言·人工智能·后端·rust·操作系统·os