spring boot发送邮件

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就说明这个方法没有问题,这个时候我们去邮箱看一下,发现可以收到这封邮件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值