spring boot发送邮件

项目目录结构

在这里插入图片描述

添加maven依赖

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

application.yml配置发信人信息

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

password 是授权码,不是登录密码
邮箱设置开启服务,生成授权码
在这里插入图片描述
在这里插入图片描述

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

编码测试

创建 Email 工具类 EmailUtil

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;
    }
}

测试发送邮件

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";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值