springboot实现发送邮件开箱即用

springboot实现发送邮件开箱即用

环境

jdk17

springboot版本3.2.1

依赖包

java 复制代码
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-mail</artifactId>
     <version>3.1.4</version>
</dependency>

yml配置

我用的是qq邮箱,port是465

如果用的是其他的邮箱,自己修改这个端口,可能是25

ssl:true这个必须配置,不加会报错

不要复制,自己输,复制格式会出错
邮箱就自己的邮箱
秘密要开启stmp的时候系统给那个,不是自己设置的qq邮箱秘密

java 复制代码
spring:
  mail:
    host: smtp.qq.com
    port: 465
    username: [email protected]
    password: xxxx
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true
          ssl:
            enable: true

Service层

把setFrom里的邮箱换成自己的,就yml中配置那个

java 复制代码
package com.example.demo;

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

@Service
public class EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    public void sendSimpleEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("[email protected]");
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);

        javaMailSender.send(message);
    }
}

Controller层

to后面的是收件人地址

java 复制代码
package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private EmailService emailService;

    @GetMapping("/send")
    public String sendEmail() {
        String to = "[email protected]";
        String subject = "邮件提醒";
        String text = "这是一条测试邮件";

        emailService.sendSimpleEmail(to, subject, text);

        return "邮件发送成功";
    }
}

测试

用postman直接请求对应的接口地址

不需要任何参数

测试结果如下

相关推荐
珹洺6 分钟前
计算机操作系统(十二)详细讲解调计算机操作系统调度算法与多处理机调度
android·java·数据库
fei_sun7 分钟前
【Harmony OS】作业四 布局
java·linux·网络
weixin_4293260921 分钟前
Spring MVC-面试题(33)
java·spring·mvc
为美好的生活献上中指26 分钟前
java每日精进 5.20【MyBatis 联表&分页查询】
java·tomcat·mybatis·mpj
the白勺1 小时前
Redis-基础-总结
redis·笔记·后端
不争先.1 小时前
Pycharm&&Flask 学习心得:路由(3-4)
后端·python·flask
Uranus^1 小时前
深入解析Spring Boot与Redis集成:高性能缓存实践
spring boot·redis·分布式·缓存·高性能
小马爱打代码1 小时前
Spring Boot项目配置核心 - pom.xml的依赖管理与构建优化
spring boot
冰^1 小时前
HTTP 与 HTTPS 深度解析:原理、实践与大型项目应用
java·spring boot·网络协议·spring·http·https·maven
在未来等你1 小时前
互联网大厂Java求职面试:Spring Boot 3.2+自动配置原理、AOT编译及原生镜像
java·spring boot·graalvm·aot·虚拟线程