Play framework Mailer throwing NullPointerException at maile.send() method

后端 未结 1 1771
囚心锁ツ
囚心锁ツ 2021-01-22 00:11

I am using play Mailer module. I am getting NullPointerException at mailerClient.send(email).

send mail code

import jav         


        
1条回答
  •  情歌与酒
    2021-01-22 00:44

    It looks like you incorrectly initialize MailerClient.

    The example shows that you need to inject it into the controller, that itself initialized by the Play Framework.

    You inject it into your own MailerService class. I suppose that you do something like new MailerService() in the controllers.Application.sendMailTest. As a result, MailerClient does not inject into the MailerService class (Who will do this if you initialise MailerService yourself ?)

    Solution: You need to inject MailerClient into the controller, like in the example, and then pass it into your MailerService class.

    import play.libs.mailer.Email;
    import play.libs.mailer.MailerClient;
    public class MailerService {
      MailerClient mailerClient;
    
      public MailerService(MailerClient mailerClient){
        this.mailerClient = mailerClient;
      }
    
      public void sendEmail() {
        Email email = new Email();
        email.setSubject("Activation Link");
        email.setFrom("from@gmail.com");
        email.addTo("to@gmail.com");
        email.setBodyText("hello");
        mailerClient.send(email);
      }
    }
    

    0 讨论(0)
提交回复
热议问题