美文网首页
springboot发送邮件

springboot发送邮件

作者: 祝家庄打烊 | 来源:发表于2024-01-28 16:09 被阅读0次
    邮箱开启服务

    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";
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:springboot发送邮件

          本文链接:https://www.haomeiwen.com/subject/vvbwodtx.html