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

spring.mail.username=89666XXX@qq.com

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("2431886055@qq.com", "这是一封简单邮件", "这是一封普通的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("2431886055@qq.com", "这是一封模板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("2431886055@qq.com", "这是一封带附件的邮件", "邮件中有附件,请注意查收!", url.getPath());
        return "ok";
    }



}
复制代码
七、postman测试
复制代码
(1)第一个简单邮件
复制代码
效果
复制代码
(2)第二个带模板的邮件
复制代码
效果
复制代码
(3)第三个带附件的邮件
复制代码
效果
复制代码
 
相关推荐
SimonKing几秒前
拯救大文件上传:一文彻底彻底搞懂秒传、断点续传以及分片上传
java·后端·架构
深栈解码几秒前
JUC并发编程 内存布局和对象头
java·后端
北方有星辰zz14 分钟前
数据结构:栈
java·开发语言·数据结构
Seven9715 分钟前
一个static关键字引发的线上故障:深度剖析静态变量与配置热更新的陷阱
java
山野万里__17 分钟前
C++与Java内存共享技术:跨平台与跨语言实现指南
android·java·c++·笔记
风象南19 分钟前
Spring Shell命令行工具开发实战
java·spring boot·后端
Java技术小馆23 分钟前
POST为什么发送两次请求
java·面试·架构
天天摸鱼的java工程师24 分钟前
MySQL表设计实战指南:从业务场景到表结构优化
java·后端·mysql
SimonKing27 分钟前
Java处理PDF就靠它!Apache PDFBox:开源免费的PDF全能王
java·后端·程序员
天天摸鱼的java工程师31 分钟前
Java与AI:从业务场景到代码实现,构建人工客服系统实战
java·后端·面试