📑前言
本文主要是【SpringBoot】——SpringBoot项目发送邮件的文章,如果有什么需要改进的地方还请大佬指出⛺️
🎬作者简介:大家好,我是听风与他🥇
☁️博客首页:CSDN主页听风与他
🌄每日一句:狠狠沉淀,顶峰相见
目录
- 📑前言
- SpringBoot项目发送邮件
- springboot整合mail发送邮件
- 1.在pom.xml中导入邮件发送依赖
- 2.配置yml文件中mail的信息
- 3.编写邮件发送类EmailSending
- 4.编写测试类EmailSendApplicationTests
- 📑文章末尾
SpringBoot项目发送邮件
springboot整合mail发送邮件
1.在pom.xml中导入邮件发送依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
2.配置yml文件中mail的信息
mail:host: smtp.163.com #邮箱采用的是网易邮箱,也可以更换其他的邮箱username: 15671190765@163.compassword: xxxx #配置邮箱的snmp验证信息
3.编写邮件发送类EmailSending
package com.emailsend.listener;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.Component;import java.util.Random;@Component
public class EmailSending {@AutowiredJavaMailSender sender;@Value("${spring.mail.username}")String username;private SimpleMailMessage createMessage(String title, String content, String email){SimpleMailMessage message = new SimpleMailMessage();message.setSubject(title); //主题message.setText(content); //内容message.setTo(email); //发送目标邮箱message.setFrom(username); //源发送邮箱return message;}public void sendMailMessage(String email){Random random = new Random();int code = random.nextInt(899999)+100000;SimpleMailMessage message= this.createMessage("欢迎注册我们的网站","您的验证码为"+(code)+",有效时间三分钟,为了保障您的安全,请勿向他人泄露验证码信息。",email);if (message == null) return;sender.send(message);}
}
4.编写测试类EmailSendApplicationTests
package com.emailsend;import com.emailsend.listener.EmailSending;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class EmailSendApplicationTests {@Autowiredprivate EmailSending emailSending;@Testvoid contextLoads() {emailSending.sendMailMessage("2482893650@qq.com");}}