Skip to content

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 –

public class OtpEmailController {
    private EmailSenderService emailService;

    Random random = new Random(1000);
    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 :

public class EmailSenderService {

    private JavaMailSender mailSender;
    public void sendMail(String toEmail,
                         String subject,
                         String body) {
        SimpleMailMessage message=new SimpleMailMessage();
        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( ~[classes/:na]
    at com.example.sessionHandling.sessionHandling.controller.SessionHandlingController.loginUser( ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke( ~[na:na] 

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



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

You can add @Autowired annotation:

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.