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","标题","正文");
    }
}
相关推荐
幽络源小助理14 小时前
最新短网址系统源码 分用户链接 - 幽络源免费源码分享
前端·php
Muen14 小时前
SwiftUI-学习路线
前端
小小小小宇14 小时前
普通 H5 新版本部署后通知用户更新方案
前端
JAVA学习通14 小时前
开云集致 Java开发 实习 一面
java·开发语言
jimy114 小时前
在新磁盘挂载点/data安装codex
服务器
小陈工14 小时前
Python异步编程进阶:asyncio高级模式与性能调优
开发语言·前端·数据库·人工智能·python·flask·numpy
阿旭超级学得完14 小时前
C++11(初始化)
java·开发语言·数据结构·c++·算法
小小小小宇14 小时前
App 内嵌 H5 秒开技术方案
前端
烛阴15 小时前
TEngine 入门系列(二):三件套环境搭建 -- Unity + TEngine + AI 助手
前端·c#·unity3d
一只大袋鼠15 小时前
SpringMVC全局异常处理
java·开发语言·springmvc·javaweb