Home > Blockchain >  Getting error while sending alert emails to all due items in DB using springboot
Getting error while sending alert emails to all due items in DB using springboot

Time:06-16

I am developing an api using Springboot, which will check the DB and find all the email ids in an action table and send alert emails.I could start the springboot applciation with no error. But when i send the http://localhost:8082/send-due-emails request in postman, I get the below error in the application

Cannot invoke "com.emailschedulerfinal.repository.EmailRepository.findDueEmails()" because "this.emailrepo" is null

The query I use is returning the results in DB. It has got two email ids in the results. Can you please help me with this issue? Anything wrong in the way I gave the query in the repository? Or any issue with the return statements here?

This is my Controller

@RestController
public class EmailController {

    SchedulerService schedulerservice = new SchedulerService(null);
    @RequestMapping("send-due-emails")
    public String send() {
        try {
            schedulerservice.sendEmailIds();
        } catch (MailException mailException) {
            System.out.println(mailException);
        }
        return "Congratulations! Your mail has been sent to the user.";
    }

}

This is my model

@Entity
@Table(name = "actionitems")
public class actionitems {
    
    @Id
    @GeneratedValue
    private int id;
    private String action;
    private String email;
    private Date duedate;
#getters and setters omitted here
}

This is my repository

    public interface EmailRepository extends JpaRepository<actionitems, Long> {
       @Query("select email from actionitems where duedate< CURRENT_TIMESTAMP")     
       public List<String[]> findDueEmails();
                    
}

This is my service

public class SchedulerService {
    private JavaMailSender javaMailSender;
    
    @Autowired
    EmailRepository emailrepo;


    public SchedulerService(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public List<String[]> findDueEmailsFromDB() {
        
        return emailrepo.findDueEmails();
    }
    
    public void sendEmailIds() {
        
        List<String[]> To = findDueEmailsFromDB();
        String k[] = To.toArray(new String[To.size()]);
        
        System.out.println("The list obtained is "   k);
         
        // Iterating over above string array
        for (String str : k) {
 
            // Printing the elements in above array
            System.out.println(str);
        }
       

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(k);
        mailMessage.setSubject("sample subject");
        mailMessage.setText("Sample text");
        mailMessage.setFrom("[email protected]");
        javaMailSender.send(mailMessage);
        }
}

CodePudding user response:

I got a workaround for this. Instead of using query annotations, if I write a utility class which connect to db and run the query and return the results, it is sending emails to all those email ids .But still I would like to know how to make the same work using @Query annotation in springboot.

 public static Connection connect() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
    public static ArrayList<String> getdueEmails() throws SQLException, ClassNotFoundException{
        ArrayList<String> a = new ArrayList<String>();

        Connection con = connect();
        PreparedStatement ps = con.prepareStatement("select email from actionitems_final where duedate< CURRENT_TIMESTAMP");
        ResultSet rs = ps.executeQuery();
       

        while(rs.next())
        {
            a.add(rs.getString(1));
        }

        return a;
    }

This is my service

public void sendEmail() throws MailException, ClassNotFoundException, SQLException {

    SQLhelper sqlhelper = new SQLhelper();
    /*
     * This JavaMailSender Interface is used to send Mail in Spring Boot. This
     * JavaMailSender extends the MailSender Interface which contains send()
     * function. SimpleMailMessage Object is required because send() function uses
     * object of SimpleMailMessage as a Parameter
     */
    List<String> To = sqlhelper.getdueEmails();
    String k[] = To.toArray(new String[To.size()]);

    SimpleMailMessage mail = new SimpleMailMessage();

    mail.setTo(k);
    mail.setSubject("Email to all persons having due date");
    mail.setText("This is sent to all email ids corresponding to actions which are due today...");

    /*
     * This send() contains an Object of SimpleMailMessage as an Parameter
     */
    javaMailSender.send(mail);
}

CodePudding user response:

Finally I found the issue with my query annotation. Earlier both the model class name and my DB table name were the same. We have to use the model class name inside the query annoatation and not the db table name.

This is my repository

public interface EmailRepository extends JpaRepository<ActionItems, String> {
    @Query("select email from ActionItems where duedate< CURRENT_TIMESTAMP")
    List<String> finddueemailsfromdb();

}

This is my entity

@Entity
@Table(name = "actionitemsFinal")
public class ActionItems {
    
    @Id
    @GeneratedValue
    private int id;
    private String action;
    private String email;
    private Date duedate;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAction() {
        return action;
    }
    public void setAction(String action) {
        this.action = action;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Date getDuedate() {
        return duedate;
    }
    public void setDuedate(Date duedate) {
        this.duedate = duedate;
    }

}

This is my Service

List<String> To = emailrepo.finddueemailsfromdb();
String k[] = To.toArray(new String[To.size()]);
SimpleMailMessage mail = new SimpleMailMessage();
/* mail.setTo(actions.getEmailAddress()); */
mail.setTo(k);
  ......rest of the code omitted
  • Related