Springboot 自动发送邮件

完成Springboot配置发件邮箱,自动给其他邮箱发送邮件功能

一、创建springboot基础项目,引入依赖

复制代码
<!-- Spring Boot 邮件依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Spring Boot 模板依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

二、配置文件添加必要的配置:

复制代码
#qq邮箱为例
复制代码
spring.mail.host=smtp.qq.com

spring.mail.port=465

[email protected]

spring.mail.password=XXXXXX  #不是邮件密码而是授权码(邮箱设置里获取)

spring.mail.protocol=smtp

spring.mail.test-connection=true

spring.mail.default-encoding=UTF-8

spring.mail.properties.mail.smtp.auth=true

spring.mail.properties.mail.smtp.starttls.enable=true

spring.mail.properties.mail.smtp.starttls.required=true

spring.mail.properties.mail.smtp.ssl.enable=true

spring.mail.properties.mail.display.sendmail=spring-boot-demo

三、工程结构

复制代码
四、MailService接口
复制代码
package com.example.mail.demo;

import javax.mail.MessagingException;

public interface MailService {
    /**
     * 发送文本邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     */
    void sendSimpleMail(String to, String subject, String content, String... cc);

    /**
     * 发送HTML邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     * @throws MessagingException 邮件发送异常
     */
    void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException;

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人地址
     * @param subject  邮件主题
     * @param content  邮件内容
     * @param filePath 附件地址
     * @param cc       抄送地址
     * @throws MessagingException 邮件发送异常
     */
    void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException;

   
}
复制代码
五、MailServiceImpl实现
复制代码
package com.example.mail.demo;
 
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.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailServiceImpl implements MailService {

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

    /**
     * 发送文本邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content, String... cc) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        if (cc != null) {
            message.setCc(cc);
        }
        mailSender.send(message);
    }

    /**
     * 发送HTML邮件
     *
     * @param to      收件人地址
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param cc      抄送地址
     * @throws MessagingException 邮件发送异常
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        if (cc != null) {
            helper.setCc(cc);
        }
        mailSender.send(message);
    }

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人地址
     * @param subject  邮件主题
     * @param content  邮件内容
     * @param filePath 附件地址
     * @param cc       抄送地址
     * @throws MessagingException 邮件发送异常
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        if (cc != null) {
            helper.setCc(cc);
        }
        FileSystemResource file = new FileSystemResource(new File(filePath));

        String fileName = new File(filePath).getName();
        System.out.println("fileName:"+fileName);
        helper.addAttachment(fileName, file);

        mailSender.send(message);
    }


}
复制代码
六、EmailController控制类
复制代码
package com.example.mail.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import java.io.File;
import java.net.URL;

@Controller
public class EmailController {

    @Autowired
    private MailService mailService;

    /**
     * 测试发送简单邮件
     */
    @GetMapping("/testSendSimpleMail")
    @ResponseBody
    public String sendSimpleMail() {
        mailService.sendSimpleMail("[email protected]", "这是一封简单邮件", "这是一封普通的SpringBoot测试邮件");
        return "ok";
    }

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送html邮件
     * @return
     * @throws MessagingException
     */
    @GetMapping("/sendHtmlMail")
    @ResponseBody
    public String sendHtmlMail() throws MessagingException {
        Context context = new Context();
        context.setVariable("project", "Spring Boot email");
        context.setVariable("author", "万笑佛");
        context.setVariable("url", "https://www.cnblogs.com/yclh/");
        String emailTemplate = templateEngine.process("welcome", context);
        mailService.sendHtmlMail("[email protected]", "这是一封模板HTML邮件", emailTemplate);
        return "ok";
    }


    /**
     * 发送带附件的邮件
     * @throws MessagingException
     */
    @GetMapping("/sendAttachmentsMail")
    @ResponseBody
    public String sendAttachmentsMail() throws MessagingException {
        URL url = null;
        try {
            // 创建一个文件对象
            File file = new File("D:\\IDEANew\\45Mail\\src\\main\\resources\\static\\index.html");
            // 将文件对象转换为URI
            url = file.toURI().toURL();
            // 输出URL
            System.out.println("文件的URL: " + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(url.getPath());
        mailService.sendAttachmentsMail("[email protected]", "这是一封带附件的邮件", "邮件中有附件,请注意查收!", url.getPath());
        return "ok";
    }



}
复制代码
七、postman测试
复制代码
(1)第一个简单邮件
复制代码
效果
复制代码
(2)第二个带模板的邮件
复制代码
效果
复制代码
(3)第三个带附件的邮件
复制代码
效果
复制代码
 
相关推荐
熊大如如2 小时前
Java 反射
java·开发语言
猿来入此小猿2 小时前
基于SSM实现的健身房系统功能实现十六
java·毕业设计·ssm·毕业源码·免费学习·猿来入此·健身平台
goTsHgo3 小时前
Spring Boot 自动装配原理详解
java·spring boot
卑微的Coder3 小时前
JMeter同步定时器 模拟多用户并发访问场景
java·jmeter·压力测试
pjx9873 小时前
微服务的“导航系统”:使用Spring Cloud Eureka实现服务注册与发现
java·spring cloud·微服务·eureka
多多*4 小时前
算法竞赛相关 Java 二分模版
java·开发语言·数据结构·数据库·sql·算法·oracle
爱喝酸奶的桃酥4 小时前
MYSQL数据库集群高可用和数据监控平台
java·数据库·mysql
唐僧洗头爱飘柔95275 小时前
【SSM-SSM整合】将Spring、SpringMVC、Mybatis三者进行整合;本文阐述了几个核心原理知识点,附带对应的源码以及描述解析
java·spring·mybatis·springmvc·动态代理·ioc容器·视图控制器
骑牛小道士5 小时前
Java基础 集合框架 Collection接口和抽象类AbstractCollection
java
alden_ygq5 小时前
当java进程内存使用超过jvm设置大小会发生什么?
java·开发语言·jvm