本文主要是【SpringBoot】——SpringBoot项目发送邮件的文章,如果有什么需要改进的地方还请大佬指出⛺️
作者简介:大家好,我是听风与他
☁️博客首页:CSDN主页听风与他
每日一句:狠狠沉淀,顶峰相见
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-mailartifactId>
dependency>
mail:
host: smtp.163.com #邮箱采用的是网易邮箱,也可以更换其他的邮箱
username: [email protected]
password: xxxx #配置邮箱的snmp验证信息
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 {
@Autowired
JavaMailSender 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);
}
}
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 {
@Autowired
private EmailSending emailSending;
@Test
void contextLoads() {
emailSending.sendMailMessage("[email protected]");
}
}