1. 首页
  2. 软件开发
  3. JAVA
  4. Spring Boot整合发送QQ邮箱功能

Spring Boot整合发送QQ邮箱功能

  • 发布于 2024-08-14
  • 0 次阅读

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

1. 创建 Spring Boot 项目

使用 Spring Initializr(https://start.spring.io/)创建一个新的 Spring Boot 项目,并添加spring-boot-starter-mail依赖。

2. 添加配置

在application.properties或application.yml文件中添加 QQ 邮箱的 SMTP 配置。这里以application.yml为例:

spring:
  mail:
    host: smtp.qq.com
    port: 465
    username: your-qq-email@qq.com # 你的QQ邮箱地址
    password: your-qq-auth-code # 你的QQ邮箱授权码
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
          ssl:
            enable: true

请确保将your-qq-email@qq.com和your-qq-auth-code替换为实际的 QQ 邮箱地址和授权码。

3. 创建邮件服务

在项目中创建一个名为EmailService.java的类,用于封装邮件发送的逻辑:

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    public void sendSimpleEmail(String to, String subject, String content) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom("your-qq-email@qq.com"); // 发件人地址
        helper.setTo(to); // 收件人地址
        helper.setSubject(subject); // 邮件主题
        helper.setText(content); // 邮件内容

        try {
            mailSender.send(mimeMessage);
            System.out.println("Email sent successfully.");
        } catch (Exception e) {
            System.err.println("Failed to send email: " + e.getMessage());
        }
    }
}

同样地,请将your-qq-email@qq.com替换为你的 QQ 邮箱地址。

4. 调用邮件服务

在 Controller 或其他需要发送邮件的地方调用EmailService的sendSimpleEmail方法:

package com.example.demo.controller;

import com.example.demo.service.EmailService;
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("/send-email")
    public String sendEmail() {
        String to = "recipient-email@example.com"; // 收件人邮箱地址
        String subject = "Test Email from QQ"; // 邮件主题
        String content = "Hello, this is a test email sent from QQ."; // 邮件内容

        emailService.sendSimpleEmail(to, subject, content);

        return "Email sending initiated.";
    }
}

请将recipient-email@example.com替换为实际的收件人邮箱地址。

5. 运行项目

启动 Spring Boot 项目,并访问