欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

spring发送邮件

时间:2023-07-01
spring boot项目配置邮件发送(以qq邮箱为例) 引入坐标依赖

org.springframework.boot spring-boot-starter-mail

添加springboot项目基础依赖后直接添加mail的依赖即可

yml文件配置

application.yml

# 需要开启 smtpspring: mail: host: smtp.qq.com port: 465 username: 1783292088@qq.com password: dgmirqbblbjncfeh properties: mail: smtp: ssl: enable: true

其中主要就是配置了发送方邮件的账户和密码(密码指的是邮箱的授权码)
如下图所示
![在这里插入图片描述](https://img-blog.csdnimg.cn/b04b8e9951964693adf2430d2d8c7335.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5L2gT0sg5oiR5b6u56yR,size_20,color_FFFFFF,t_70,g_se,x_16

接口代码

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.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/mail")public class MailController { @Autowired JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String from; @GetMapping("/sendMessage") public void sendMessageMail() { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo("jinyu@micous.com"); message.setSubject("验证码"); message.setText("77886"); javaMailSender.send(message); }}

编写单元测试类

import com.demo.DemoMailApplication;import jdk.net.SocketFlow;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.http.MediaType;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.MvcResult;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@RunWith(SpringJUnit4ClassRunner.class)@AutoConfigureMockMvc@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = DemoMailApplication.class)public class DemoTest { @Autowired MockMvc mockMvc; @Test public void testMail() throws Exception { MvcResult mvcResult = mockMvc.perform( get("http://localhost:8080/mail/sendMessage") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); System.out.println(mvcResult.getResponse().getContentAsString()); }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。