0

I'm working on a project in which my intention is to run a Corn job and send mail to my friends to wishing them on their birthday, I was able to get email from MySQL DB and compared it to the current date but when it comes to sending an email I'm getting NullPointerException.

I'm sure there is no problem with application properties I used them with other projects as well and they are function properly

//Imports
package dev.teja.happybirthday;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.persistence.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.Email;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;

//Main
@SpringBootApplication
public class HappybirthdayApplication {
    public static void main(String[] args) {
        SpringApplication.run(HappybirthdayApplication.class, args);
    }
    @Autowired
    MyFriendsRepository myFriendsRepository ;
    @Scheduled(cron = "*/30 * * * * *")
    void WishMyFriends() {
        List<MyFriends> myFriendsList = myFriendsRepository.findAll();
        myFriendsList.forEach(friend -> {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
            String CurrentDate= formatter.format(date);
            String GivenDate = formatter.format(friend.dob);
            if (GivenDate.equals(CurrentDate)){
                Job job = new Job();
                Map<String, Object> model = new HashMap<>();
                model.put("Name",friend.name);
                job.sendWish(friend.email,model);
            }
        });
    }
}
@Configuration
@ConditionalOnProperty(name = "scheduling.enabled", matchIfMissing = true)
@EnableScheduling
class Tasks {
}
//Model
@Data
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
class MyFriends {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
    String name;
    @Email
    @Column(unique = true)
    String email;
    @JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
    Date dob;
    Long phoneNumber;
}
//Repository
interface MyFriendsRepository extends JpaRepository<MyFriends, Long> {
}
@RestController
@RequestMapping("/")
class FriendsController {
    @Autowired
    MyFriendsRepository myFriendsRepository;
    @PostMapping("/friends")
    ResponseEntity<MyFriends> createFriend(@RequestBody MyFriends myFriend) {
        myFriendsRepository.save(myFriend);
        return new ResponseEntity<MyFriends>(myFriend, HttpStatus.CREATED);
    }
    @GetMapping("/friends")
    List<MyFriends> getFriends() {
        return myFriendsRepository.findAll();
    }
}
//Interface
interface wisher{
    void sendWish(String email, Map<String, Object> model);
}
//Implementation
@Service
class Job implements wisher{
    @Autowired
    private JavaMailSender sender;
    @Autowired
    private freemarker.template.Configuration config;
    @Override
    public void sendWish(String email,Map<String, Object> model) {
        System.out.println("wishes sent to "+ email);
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                    StandardCharsets.UTF_8.name());
            Template template = config.getTemplate("new-template.ftl");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            helper.setTo(email);
            helper.setFrom("kondasaitej@gmail.com");
            helper.setSubject("Happy Birthday");
            helper.setText(html,true);
            sender.send(message);
        } catch (MessagingException | IOException | TemplateException e) {
            e.printStackTrace();
        }
    }
}

Friends Table

FreeMaker file in ./resources/Templates

/**
 * FREEMAKER new-template.ftl
 * <html xmlns="http://www.w3.org/1999/xhtml">
 * <head>
 *     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 *     <title>Comment Alert Mail</title>
 * </head>
 * <body>
 * <p>happy birthday ${Name}</p>
 * </body>
 */

This is the error I'm getting this following


Hibernate: select myfriends0_.id as id1_0_, myfriends0_.dob as dob2_0_, myfriends0_.email as email3_0_, myfriends0_.name as name4_0_, myfriends0_.phone_number as phone_nu5_0_ from my_friends myfriends0_
wishes sent to kondasaitej@protonmail.com
2020-09-26 21:01:52.012 ERROR 84242 --- [   scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task

java.lang.NullPointerException: null
    at dev.teja.happybirthday.Job.sendWish(HappybirthdayApplication.java:115) ~[classes/:na]
    at dev.teja.happybirthday.HappybirthdayApplication.lambda$WishMyFriends$0(HappybirthdayApplication.java:53) ~[classes/:na]
    at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_251]
    at dev.teja.happybirthday.HappybirthdayApplication.WishMyFriends(HappybirthdayApplication.java:44) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_251]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_251]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_251]
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) [spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_251]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_251]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_251]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [na:1.8.0_251]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_251]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_251]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_251]

  • Did you tried debugging to see exact line NPE is getting thrown? – Sridhar Patnaik Sep 26 '20 at 16:14
  • No Sridhar! can you instruct me how to do it? – saiteja konda Sep 26 '20 at 16:31
  • 1
    I suspect @Autowired private JavaMailSender sender; this is not getting autowired somehow and it is NULL. – Alien Sep 26 '20 at 17:56
  • I tried changing it from private JavaMailSender sender; to JavaMailSender sender; – saiteja konda Sep 26 '20 at 18:29
  • 2
    From looking at the code and logs,I think ,the problem is at line job.sendWish(friend.email,model); . Probably email is coming null.What you can do is Run the application in Debug mode and put a debug point at this line and then check values of friend and email.Here is the link which tells how to run Spring boot application in Debug mode.https://stackoverflow.com/questions/24113939/how-to-debug-spring-boot-application-with-eclipse – javaguy Sep 26 '20 at 18:37
  • The stacktrace says the NPE is happening on line 115 of `HappybirthdayApplication.java`. Which line of the `sendWish` method is that? – Ole V.V. Sep 27 '20 at 05:20
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Ole V.V. Sep 27 '20 at 05:22

2 Answers2

1

Try add getting in the @Autowired private JavaMailSender sender;

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

I think you have not implemented your JavaMailSender bean. Define a bean like below. Then your @Autowire annotation will work.

@Bean
public JavaMailSender getJavaMailSender() 
{
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(25);
      
    mailSender.setUsername("admin@gmail.com");
    mailSender.setPassword("password");
      
    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");
      
    return mailSender;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Angshuman
  • 225
  • 3
  • 17