SpringBoot配合QQ邮箱发送邮件

先在maven中添加依赖

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

然后在yml文件中配置信息

spring:
  # 发送邮件配置
  mail:
    host: smtp.qq.com # 配置 smtp 服务器地址
    port: 587 # smtp 服务器的端口
    username: 你的qq号@qq.com # 配置邮箱用户名(你的邮箱地址)
    password: 你的授权码 # 配置申请到的授权码(刚让复制的授权码)
    default-encoding: UTF-8 # 配置邮件编码
    properties:
      mail:
        smtp:
          auth: true
          socketFactoryClass: javax.net.ssl.SSLSocketFactory # 配饰 SSL 加密工厂
        debug: true
    from: 你的qq号@qq.com # 发送方邮件,配在yml中可方便更改

新建EmailUtil工具类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

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

@Component //后续工具类被调用的时候,方便依赖注入
public class EmailUtil {
    @Value("${spring.mail.from}") // 从application.yml配置文件中获取
    private String from; // 发送发邮箱地址

    @Autowired
    private JavaMailSender mailSender;


    /**
     * 发送纯文本邮件信息
     * @param to      接收方
     * @param subject 邮件主题
     * @param content 邮件内容(发送内容)
     */
    public void sendMessage(String to, String subject, String content) {
        // 创建一个邮件对象
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(from); // 设置发送方
        msg.setTo(to); // 设置接收方
        msg.setSubject(subject); // 设置邮件主题
        msg.setText(content); // 设置邮件内容
        // 发送邮件
        mailSender.send(msg);
    }


    /**
     * 发送带1个附件的邮件信息
     * @param to      接收方
     * @param subject 邮件主题
     * @param content 邮件内容(发送内容)
     * @param file 单个文件
     */
    public void sendMessage(String to, String subject, String content, File file) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setFrom(from); // 设置发送方
            helper.setTo(to); // 设置接收方
            helper.setSubject(subject); // 设置邮件主题
            helper.setText(content); // 设置邮件内容
            helper.addAttachment(file.getName(), file); // 添加附件(单个)
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        // 发送邮件
        mailSender.send(mimeMessage);
    }


    /**
     * 发送带多个附件的邮件信息
     * @param to      接收方
     * @param subject 邮件主题
     * @param content 邮件内容(发送内容)
     * @param files 多个文件
     */
    public void sendMessage(String to, String subject, String content, List<File> files) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setFrom(from); // 设置发送发
            helper.setTo(to); // 设置接收方
            helper.setSubject(subject); // 设置邮件主题
            helper.setText(content); // 设置邮件内容
            if (files != null && files.size() > 0) { // 添加附件(多个)
                for (File file : files) {
                    helper.addAttachment(file.getName(), file);
                }
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        // 发送邮件
        mailSender.send(mimeMessage);
    }


    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }
}

测试类进行测试

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Sheet;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class SendMailApplicationTests {
    @Autowired
    private EmailUtil emailUtil;

    @Test
    void sendStringEmail() {
        // 测试文本邮件发送(无附件)
        String to = "接收方@126.com"; // 这是个假邮箱,写成你自己的邮箱地址就可以
        String title = "标题";
        String content = "内容";
        emailUtil.sendMessage(to, title, content);
    }

    @Test
    void sendFileEmail() {
        // 测试单个附件邮件发送
        String to = "接收方@126.com"; // 这是个假邮箱,写成你自己的邮箱地址就可以
        String title = "标题";
        String content = "内容";
        File file = new File("C:\\Users\\Administrator\\Desktop\\1.jpg");
        emailUtil.sendMessage(to, title, content, file);
    }

    @Test
    void sendFilesEmail() {
        // 测试多个附件邮件发送
        String to = "接收方@126.com"; // 这是个假邮箱,写成你自己的邮箱地址就可以
        String title = "标题";
        String content = "内容";
        List<File> files=new ArrayList<>();
        files.add(new File("C:\\Users\\Administrator\\Desktop\\1.jpg"));
        files.add(new File("C:\\Users\\Administrator\\Desktop\\2.png"));
        emailUtil.sendMessage(to, title, content, files);
    }

    @Test
    void sendMatrixEmail() {
        // 测试递增矩阵的邮件发送(核心是IO流,在线生成excel文件
        String to = "接收方@126.com"; // 这是个假邮箱,写成你自己的邮箱地址就可以
        String title = "标题";
        String content = "内容";

        File file = new File("matrix.xlsx"); //excel的文件名
        try (Workbook workbook = WorkbookFactory.create(true)) {
            Sheet sheet = workbook.createSheet("sheet1"); //第一个页签的名字

            //定义m行n列的矩阵
            int m=6;
            int n=9;

            // 写入数据
            for (int i = 0; i < m; i++) { //表示总共只写m行
                Row dataRow = sheet.createRow(i); //这是行变量,表示从第0行开始写
                Cell dataCell; //每次循环,都要重新定义单元格变量
                for (int j = 0; j < n; j++) { //表示总共只写n列
                    dataCell = dataRow.createCell(j); //对于每一 行变量而言,实际从第0列开始写入。指向每个单元格变量
                    dataCell.setCellValue(n*i+1 + j); //单元格设置 值
                }
            }

            // 写入文件
            //try (FileOutputStream fileOut = new FileOutputStream("./out.xlsx")) { //写入到本地文件
            try (FileOutputStream fileOut = new FileOutputStream(file)) { //写入到上面这个临时变量文件(变量名已经定义过
                workbook.write(fileOut);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        emailUtil.sendMessage(to, title, content, file);
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Spring Boot发送邮件的步骤: 1. 导入Spring Boot提供的依赖[^1]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 2. 在配置文件中设置邮箱信息: ```properties spring.mail.host=smtp.qq.com spring.mail.port=587 spring.mail.username=your-email@qq.com spring.mail.password=your-email-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 3. 创建一个邮件服务类,用于发送邮件[^2]: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender mailSender; public void sendEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); mailSender.send(message); } } ``` 4. 在需要发送邮件的地方调用邮件服务类的方法发送邮件: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class EmailController { @Autowired private EmailService emailService; @GetMapping("/sendEmail") public String sendEmail() { String to = "recipient@example.com"; String subject = "Test Email"; String text = "This is a test email."; emailService.sendEmail(to, subject, text); return "Email sent successfully."; } } ``` 以上是使用Spring Boot发送邮件的简单示例。你可以根据自己的需求进行相应的配置和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值