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)第三个带附件的邮件
复制代码
效果
复制代码
 
相关推荐
这孩子叫逆几秒前
Spring Boot项目的创建与使用
java·spring boot·后端
星星法术嗲人4 分钟前
【Java】—— 集合框架:Collections工具类的使用
java·开发语言
一丝晨光23 分钟前
C++、Ruby和JavaScript
java·开发语言·javascript·c++·python·c·ruby
天上掉下来个程小白25 分钟前
Stream流的中间方法
java·开发语言·windows
xujinwei_gingko36 分钟前
JAVA基础面试题汇总(持续更新)
java·开发语言
liuyang-neu37 分钟前
力扣 简单 110.平衡二叉树
java·算法·leetcode·深度优先
一丝晨光1 小时前
Java、PHP、ASP、JSP、Kotlin、.NET、Go
java·kotlin·go·php·.net·jsp·asp
罗曼蒂克在消亡1 小时前
2.3MyBatis——插件机制
java·mybatis·源码学习
_GR1 小时前
每日OJ题_牛客_牛牛冲钻五_模拟_C++_Java
java·数据结构·c++·算法·动态规划
无限大.1 小时前
c语言200例 067
java·c语言·开发语言