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","标题","正文");
    }
}
相关推荐
Hyyy19 分钟前
Function Calling / Tool Use的原理和实现模式
前端·llm·ai编程
爱勇宝26 分钟前
从 Ctrl+CV 到 Enter:程序员正在失去什么
前端·后端·程序员
徐小夕44 分钟前
我们开源了一款“框架无关”的思维导图编辑器,3分钟集成到任意系统
前端·javascript·github
PBitW1 小时前
GPT训练我的第三天,明白了应该咋说满分回答!😕😕😕
前端·javascript·面试
像我这样帅的人丶你还1 小时前
Java 后端详解(四):分页与搜索
java·javascript·后端
她的男孩1 小时前
数据权限为什么不能只靠注解?Forge 的 Mapper 层 SQL 改写源码拆解
java·后端·架构
摸着石头过河的石头1 小时前
前端多仓库管理:从混乱到有序的进化之路
前端
星栈1 小时前
写 Dioxus Demo 不难,难的是把它写成项目
前端·rust·前端框架
labixiong1 小时前
还原一个完整符合规范的 Promise(二)
前端·javascript
时光足迹2 小时前
腾讯云 TRTC UniApp SDK 从入门到上线
前端·vue.js·uni-app