springboot实现发送邮件开箱即用

springboot实现发送邮件开箱即用

环境

jdk17
springboot版本3.2.1

依赖包

<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邮箱秘密

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中配置那个

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后面的是收件人地址

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直接请求对应的接口地址
不需要任何参数
测试结果如下
在这里插入图片描述

在这里插入图片描述

相关推荐

  1. springboot发送邮件

    2023-12-24 19:20:02       15 阅读
  2. Springboot使用Hutool工具类实现邮件发送

    2023-12-24 19:20:02       31 阅读
  3. 前端websocket实体类,开箱

    2023-12-24 19:20:02       40 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-24 19:20:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-24 19:20:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-24 19:20:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-24 19:20:02       20 阅读

热门阅读

  1. 迭代器模式(Iterator)

    2023-12-24 19:20:02       38 阅读
  2. 408真题笔记

    2023-12-24 19:20:02       30 阅读
  3. 微服务项目遇到的小问题

    2023-12-24 19:20:02       38 阅读
  4. 如何在Vim/Vi中使用“搜索”功能

    2023-12-24 19:20:02       41 阅读
  5. IO的多路复用

    2023-12-24 19:20:02       44 阅读
  6. 交叉熵损失(Cross Entropy Loss)学习笔记

    2023-12-24 19:20:02       39 阅读
  7. 3.架构设计系列:高并发系统的设计目标

    2023-12-24 19:20:02       38 阅读