我想搭建一个简单的邮件发送工具内,但是我不知道为什么,每次都要报java.lang.NullPointerException
util:
//邮件验证工具集合
package com.zzj.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class demo01 {
@Autowired
private static JavaMailSender mailSender;
public static boolean Emailsend(String Email, int code) {
// 判断邮箱是否存在
# MybatisUtil.ifEmail(Email) 是指判断当前数据库有没有对应的数据,有返回true没有返回false。这里默认返回true
if (MybatisUtil.ifEmail(Email)) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom("875198099@qq.com");
simpleMailMessage.setTo(Email);
simpleMailMessage.setSubject("邮箱验证");
simpleMailMessage.setText("您的【" + Email + "】验证码是:" + code + ",提供给他人会导致账户被盗和财产损失,若非本人操作,请立即修改密码");
try {
mailSender.send(simpleMailMessage);
System.out.println("邮件发送成功");
return true;
} catch (MailException e) {
System.out.println("邮件发送失败" + e);
return false;
}
} else {
System.out.println("邮箱不存在");
return false;
}
}
}
测试类:
public class MysqlTest {
@Test
public void TestDemo04(){
System.out.println(demo01.Emailsend("xinjiandianziyouxiang@outlook.com",554785));
}
}
异常报错:
// 这个在报null 指针,
private static JavaMailSender mailSender;
springboot注入对象不要要static
你要是写成静态方法就不要springboot注入了。
你要是用springboot的注入那就把static都去掉,后面调用的的时候都通过springboot注入类调用。
你这个测试类也不能这么写