springboot发送邮件

邮箱开启服务

pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

application.yml

spring:
  mail:
    host: smtp.qq.com
    username: email
    password:  password
    properties:
      mail:
        smtp:
          ssl:
            enable: true

controller/SendEmail

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.*;

@RestController
public class SendEmail {

    @Value(value = "${spring.mail.username}")
    private String username;

    @Autowired
    private JavaMailSender javaMailSender;


    @GetMapping("/send-email")
    public String sendEmail(@RequestParam String to) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(username);
            message.setTo(to);
            message.setSubject("Your Verification Code");
            // 生成验证码逻辑
            String verificationCode = "123456"; // 示例验证码
            message.setText("Your verification code is: " + verificationCode);

            javaMailSender.send(message);
            return "Email sent successfully";
        } catch (Exception e) {
            e.printStackTrace();
            return "Failed to send email";
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容