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: xxxx@qq.com
    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("xxx@qq.com");
        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 = "xxx@qq.com";
        String subject = "邮件提醒";
        String text = "这是一条测试邮件";

        emailService.sendSimpleEmail(to, subject, text);

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

测试

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

不需要任何参数

测试结果如下

相关推荐
澡点睡觉9 分钟前
【golang长途旅行第32站】反射
开发语言·后端·golang
用户61204149221310 分钟前
C语言做的排队叫号系统
c语言·后端·敏捷开发
IT_陈寒29 分钟前
3年Java开发经验总结:提升50%编码效率的7个核心技巧与实战案例
前端·人工智能·后端
pengzhuofan1 小时前
Java设计模式-代理模式
java·设计模式·代理模式
现在,此刻1 小时前
from中烟科技&&翼支付 面试题1
java·面试
Victor3562 小时前
Redis(26)Redis的AOF持久化的优点和缺点是什么?
后端
Victor3562 小时前
Redis(27)如何对Redis进行备份和恢复?
后端
君不见,青丝成雪2 小时前
清分系统在电商中的一些案例
java·大数据·系统架构
叫我阿柒啊9 小时前
Java全栈开发面试实战:从基础到微服务架构
java·vue.js·spring boot·redis·git·full stack·interview
小凡敲代码9 小时前
2025年金九银十Java面试场景题大全:高频考点+深度解析+实战方案
java·程序员·java面试·后端开发·求职面试·java场景题·金九银十