使用Spring boot发送邮件

  今天尝试了一下使用Spring boot发送邮件,发现非常方便,这里做个记录

  1.可以在https://start.spring.io/直接创建项目,下载下来导入到IDEA中。

 

  2.在Spring Boot的工程中的pom.xml中引入spring-boot-starter-mail依赖:

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

maven项目会自动导入jar包,今天遇到了一次导入jar包报错的情况,去本地maven项目删除重新导入就可以了。

 

3.以QQ邮箱为例,在application.properties中加入如下配置(注意替换自己的用户名和密码):

spring.mail.host=smtp.qq.com
spring.mail.username=@qq.com
spring.mail.password=
spring.mail.default-encoding=utf-8

 

4.这里用最简单的邮件为例

package com.yh.mail.service;


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

@Service
public class mailService {
    @Value("${spring.mail.username}")
    private  String from ;

    @Autowired
    private JavaMailSender mailSender;


    public void sendSimpleMail(String to , String subject,String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(from);
        mailSender.send(message);
    }
}

 

package com.yh.mail.service;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class serviceTest {
    @Resource
    mailService mailservice;

    @Test
    public  void sendMail(){
        mailservice.sendSimpleMail("@qq.com","测试","测试");
    }
}

 

直接运行测试类就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值