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

在这里插入图片描述

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亦简_yz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值