springBoot实现发送邮箱非常的简单,加几个配置就好了,话不多说,直接上代码
首先需要去邮箱设置里面设置一下
给这两个选项都勾上,不然访问的时候会报错的。
1.在pom.xml中加入依赖
<!-- 继承spring-boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<!-- springboot每一个框架的集成都是一个starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 配置发送邮箱的核心配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
2、创建一个application.yml文件
#服务的端口
server:
port: 8033
spring:
mail:
# smtp服务器的地址
host: smtp.163.com
# 邮箱用户名
username: xxxx
# 邮箱密码
password: xxxx
# 邮箱的端口
port: 25
# 邮箱的协议
protocol: smtp
application:
# 服务的名称
name: mail-center
3.创建一个测试类
package cn.et;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class sendMailTest {
//自动装配发送邮件的类
@Autowired
private JavaMailSender jms;
@RequestMapping("send")
public String send(){
SimpleMailMessage mailMessage =new SimpleMailMessage();
//发送方的邮箱名
mailMessage.setFrom("xxxx@163.com");
//接收方的邮箱名
mailMessage.setTo("xxxx@qq.com");
//邮箱标题
mailMessage.setSubject("发送邮件");
//邮箱内容
mailMessage.setText("测试发送邮件");
jms.send(mailMessage);
return "SUCCESS";
}
}
4.创建一个启动类
package cn;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
public class Test {
public static void main(String[] args) {
SpringApplication.run(Test.class,args);
}
}
5.运行启动类,访问localhost:8033/send 效果如下:
上面我的方法写了 返回success就说明这个方法没有问题,这个时候我们去邮箱看一下,发现可以收到这封邮件