spring-boot项目实现发送qq邮箱

1、添加依赖pom.xml

复制代码
        <!-- 邮箱服务 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2、添加application.properties

复制代码
# 发件人邮箱
spring.mail.username=**********@qq.com
# QQ邮箱授权码(不是登录密码!)
spring.mail.password=**************
# 服务器
spring.mail.host=smtp.qq.com
# 端口(SSL 专用 465)
spring.mail.port=465
# 编码
spring.mail.default-encoding=UTF-8
# 必须加的 SSL 安全配置(解决 530 错误)
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

3、包装接口(可有可无)

复制代码
package com.cooker.lottery_system.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.stereotype.Component;


@Component
public class MailUtil {
    private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);
    @Value(value = "${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发邮件
     *
     * @param to:  目标邮箱地址
     * @param subject: 标题
     * @param context: 正文
     * @return
     */
    public Boolean sendSampleMail(String to, String subject, String context) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(context);
        try {
            mailSender.send(message);
        } catch (Exception e) {
            logger.error("向{}发送邮件失败!", to, e);
            return false;
        }
        return true;
    }
}

4、调用方法

复制代码
import com.cooker.lottery_system.common.utils.MailUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MailTest {
    @Autowired
    private MailUtil mailUtil;
    @Test
    void sendMail(){
        mailUtil.sendSampleMail("*******@qq.com","标题","正文");
    }
}
相关推荐
东风破_5 小时前
Docker 基础:为什么需要容器?
前端·后端·nginx
葡萄成熟时 !5 小时前
JAVA 常用API学习笔记
java·笔记·学习
东风破_5 小时前
Docker 实战:使用 Nginx 作为容器入口代理 Node 服务
前端·后端·nginx
你别说话了6 小时前
Vue项目解决跨域
前端·javascript·vue.js
Rain的Java大神之路6 小时前
介绍一下分布式事务
java·分布式·后端·spring·spring cloud·架构·springcloud
唐青枫6 小时前
http-server:别再双击 index.html,一条命令把目录变成网站
前端·javascript
暴力求解6 小时前
Linux网络---传输层协议TCP(二)
linux·服务器·开发语言·网络·tcp/ip
吴声子夜歌7 小时前
Java面试题——基础(一)
java·开发语言
网安蟹佬霸7 小时前
OSINT开源情报收集实战:从信息搜集到资产测绘(2026最新万字保姆级指南)
前端·网络·安全·web安全·网络安全·开源
南城以南溫暖如初1477 小时前
外卖CPS实战指南:从技术选型到运营落地全流程解析
java·spring boot·mysql·架构·vue