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","标题","正文");
    }
}
相关推荐
色空大师20 小时前
【网站搭建实操(一)环境部署】
java·linux·数据库·mysql·网站搭建
swipe20 小时前
AI 应用里的 Memory,不是“保存聊天记录”,而是管理上下文预算
前端·llm·agent
客卿12320 小时前
牛客刷题--找数字-- 字符串检测-字符串 双指针
java·开发语言
慧一居士21 小时前
nuxt3 项目和nuxt4 项目区别和对比
前端·vue.js
烛之武21 小时前
SpringBoot基础
java·spring boot·后端
-Da-21 小时前
Unix哲学:一切皆文件与网络通信的统一抽象
服务器·unix
威联通安全存储21 小时前
破除“重前端、轻底层”的数字幻象:如何夯实工业数据的物理底座
前端·python
Amour恋空21 小时前
Java多线程
java·开发语言·python
小胖java21 小时前
高校培养方案制定系统
java·spring
inksci21 小时前
Js生成安全随机数
前端·微信小程序