Spring Boot发送邮件

1.添加依赖

在pom.xml中添加下面的依赖

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

2、添加邮件配置参数 

(1)yml配置,(注意:mail中host的配置前缀需要是smtp),邮件可以是QQ,163,126等

spring:
  # 外置jdbc和log配置文件
  profiles:
    # 外置jdbc和log配置文件
    active: jdbc,log,redis
# 缓存配置
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml
  # thymeleaf配置
  thymeleaf:
    prefix: classpath:/templates/
    check-template-location: true
    suffix: .html
    encoding: UTF-8
    content-type: text/html
    mode: HTML5
    cache: false
 # main配置
  mail:
    host: smtp.228.com.cn
    username: xxxxxxxx@228.com.cn
    password: xxxxxx
    protocol: smtp
    port: 25

(2)properties配置

spring.mail.default-encoding=utf-8
spring.mail.host=smtp.228.com.cn
spring.mail.username=xxx@228.com.cn
spring.mail.password=xxxx
spring.mail.protocol=smtp
spring.mail.port=25

3、测试demo

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
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 MailController {
    @Autowired
    JavaMailSender javaMailSender;
    @RequestMapping("/sendMail")
    public String sendMain(){
        //建立邮件消息
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        //消息发送者
        simpleMailMessage.setFrom("xxxxxxx@228.com.cn");
        //接受者
        simpleMailMessage.setTo("xxxxxxx@qq.com");
        //消息标题
        simpleMailMessage.setSubject("测试啊");
        //内容
        simpleMailMessage.setText("哈喽啊");

        try {
            javaMailSender.send(simpleMailMessage);
        } catch (MailException ex) {
            System.err.println(ex.getMessage());
            return "fail";
        }
        return "success";
    }
}

4、测试

运行项目后打开   http://127.0.0.1:port/sendMail

测试结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值