添加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()); }}