NullPointerException while send a otp mail using springboot

I was trying to send a otp mail using springboot. I have already created a login page from where the mail will be provided to sendotp().
Or you can help by providing code for how to send mail otp using springboot.
Here is my code :

OtpControllerclass –


@Controller
public class OtpEmailController {
    
    private EmailSenderService emailService;

    Random random = new Random(1000);
    
    @PostMapping("/send-otp")
    public String sendOtp(@RequestParam("email") String email) {
        
        int otp = random.nextInt(999999);
        
        String subject = "OTP from session-handling-proj By Harshit";
        String toEmail = email;
        String body = "<h1> OTP = " + otp + "</h1>";
        
           this.emailService.sendMail(toEmail, subject, body);
          return ("success");
    }
    

EmailSenderService class :

@Service
public class EmailSenderService {

    @Autowired
    private JavaMailSender mailSender;
    
    public void sendMail(String toEmail,
                         String subject,
                         String body) {
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom("growthgreek@gamil.com");
        message.setTo(toEmail);
        message.setText(body);
        message.setSubject(subject);
        
        mailSender.send(message);
        System.out.println("message sent .....");
        
        
    }
    
}

Wnen I am calling sendOtp() method I get NullPointerException errror in springboot.

error :

java.lang.NullPointerException: null
    at com.example.sessionHandling.sessionHandling.controller.OtpEmailController.sendOtp(OtpEmailController.java:31) ~[classes/:na]
    at com.example.sessionHandling.sessionHandling.controller.SessionHandlingController.loginUser(SessionHandlingController.java:65) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na] 
............. 

I know there is some problem in OtpController but can’t figure out what exactly I have to.

>Solution :

You controller need to know that emailService should be injected by Spring.

You can add @Autowired annotation:

@Autowired
private EmailSenderService emailService;

Or create a all args constructor

OtpEmailController(EmailSenderService emailService){
  this.emailService = emailService;
}

Because class is marked as @Controller, Spring will inject beans though the constructor tying to resolve all parameters.

With second approach you can make emailService final.

Leave a Reply