1.实用idea 新建一个springboot 项目

2.在项目的maven 依赖中添加如下 依赖

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

3.在application.properties 中添加 邮箱发送账号的信息

spring.mail.host="smtp.163.com" 

spring.mail.username=邮箱账号    #发送方的邮箱
spring.mail.password=验证码或者授权码
spring.mail.properties.mail.smtp.auth=true  
spring.mail.properties.mail.smtp.starttls.enable=true  
spring.mail.properties.mail.smtp.starttls.required=true 

第三部挺闹心的,配置的时候要小心一点,一开始实用的是qq的邮箱,使用的是qq邮箱的使用总是报错误。

Could not connect to SMTP host: smtp.qq.com, port: 25;

后来查到是因为端口不对 ,端口编程465了,后来改了一下还是不对,最后直接放弃了。这里面应该有什么地方没设置好,好了,就先不管了,转战网易邮箱,亲测有效。

目前网易邮箱个qq邮箱的配置都是使用授权码了,不是密码,这个要稍微区别一下。
所以上面的spring.mail.password不要填写邮箱的登录密码

先到邮箱的设置

SpringBoot发送邮件

首先查看的是smtp 协议有没有打开

SpringBoot发送邮件

打开以后 再点击客户端授权密码

SpringBoot发送邮件

网易邮箱比较好的地方在于可以自定义授权码,而qq邮箱的授权码是随机生成的

4.代码

配置一切都ok以后,下面就是上代码了,这个相对是比价简单的

新建一个Control 在里面写上如下代码


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class Test {

    @Autowired
    JavaMailSender jms;

    @GetMapping("/send")
    public String send(){
        //建立邮件消息
        SimpleMailMessage mainMessage = new SimpleMailMessage();
        //发送者
        mainMessage.setFrom("配置文件的邮箱账号@163.com");
        //接收者
        mainMessage.setTo("接收人");
        //发送的标题
        mainMessage.setSubject("测试标题");
        //发送的内容
        mainMessage.setText("这个是测试的内容");
        jms.send(mainMessage);
        return "ok";
    }

}

启动应用访问,http://127.0.0.1:8080/send

等界面返回ok 后,登录到邮箱看下

SpringBoot发送邮件

一切都是ok 的

相关文章:

  • 2021-08-09
  • 2021-11-27
  • 2022-12-23
猜你喜欢
  • 2021-12-18
  • 2021-08-27
  • 2021-11-29
  • 2021-08-04
相关资源
相似解决方案