Stacie
Stacie

Reputation: 306

Understanding Cron in Springboot, to automate sending an email

There's a lot of information out there on Cron and I am getting slightly confused. Most of the information is solely about setting the scheduled cron annotation. I have never used SpringBoot Scheduling before. What I am trying to do is set an email to be sent once a month, say the 15th of every month. I've sent emails before using EmailService and Helpers. Is it right to combine these two methods, or should I be setting up the email template and sending of the email a different way? What I have is not sending the email (when I change to todays date and time).Can anyone tell me why it's not sending at the scheduled time, am I missing some piece of code or is this not the way to do it with Scheduling? I've used this method of sending email with email service before and its worked, so has to be something wrong with the way I set up the scheduler. Anyone have an idea on why it's not running the sendReminder() at scheduled time?

This is what I have in my code so far... Controller:

@Controller
public class MailController {
    @Autowired
    LicenseRepository licenseRepository;

    @Autowired
    InsuranceRepository insuranceRepository;

    @Autowired
    EmailService emailService;

    @Scheduled(cron = "0 15 10 15 * ?")
    public void sendReminder(){
        License license = new License();
        Insurance insurance = new Insurance();
        Mail mail = new Mail();
        mail.setFrom("[email protected]");
        mail.setTo(new String[]{"[email protected]"});
        mail.setSubject("Policy Renewal Notice");

        Map<String, Object> mailModel = new HashMap<String, Object>();
        mail.setModel(mailModel);

        try {
            emailService.sendSimpleMessage(mail, license, insurance);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    @RequestMapping(value="/email")
    public String email(){
        return "emailMessage";
    }
}

And the email service:

@Service
public class EmailService{

    private JavaMailSender javaMailSender;

    @Autowired
    public EmailService(JavaMailSender javaMailSender){
        this.javaMailSender = javaMailSender;
    }

    @Autowired
    private SpringTemplateEngine templateEngine;

    public void sendSimpleMessage(Mail mail, License license, Insurance insurance) throws MessagingException, IOException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,
                MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                StandardCharsets.UTF_8.name());

        helper.addAttachment("Mail_Icon.png", new ClassPathResource("static/images/Mail_Icon.png"));

        Context context = new Context();
        context.setVariables(mail.getModel());
        context.setVariable("license",license);
        context.setVariable("insurance",insurance);
        String html = templateEngine.process("emailMessage", context);

        helper.setTo(mail.getTo());
        helper.setText(html, true);
        helper.setSubject(mail.getSubject());
        helper.setFrom(mail.getFrom());

        javaMailSender.send(message);
    }



}

And then finally the html email template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>HTML Reminder Email</title>
    <style type="text/css">
  lots of styling here removed for easier reading
  </style>
</head>

<body bgcolor="#f6f8f1">
<table width="100%" bgcolor="#f6f8f1" border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td>
            <!--[if (gte mso 9)|(IE)]>
            <table width="600" align="center" cellpadding="0" cellspacing="0" border="0">
                <tr>
                    <td>
            <![endif]-->
            <table bgcolor="#ffffff" class="content" align="center" cellpadding="0" cellspacing="0" border="0">
                <tr>
                    <td bgcolor="#6435c9" class="header">
                        <table width="70" align="left" border="0" cellpadding="0" cellspacing="0">
                            <tr>
                                <td height="70" style="padding: 0 20px 20px 0;">
                                    <img class="fix" src="cid:Mail_Icon.png" width="70" height="70" border="0" alt="" />
                                </td>
                            </tr>
                        </table>
                        <!--[if (gte mso 9)|(IE)]>
                        <table width="425" align="left" cellpadding="0" cellspacing="0" border="0">
                            <tr>
                                <td>
                        <![endif]-->
                        <table class="col425" align="left" border="0" cellpadding="0" cellspacing="0" style="width: 100%; max-width: 425px;">
                            <tr>
                                <td height="70">
                                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                        <tr>
                                            <td class="subhead" style="padding: 0">
                                                Policy Renewal Expiration Reminder
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                        <!--[if (gte mso 9)|(IE)]>
                        </td>
                        </tr>
                        </table>
                        <![endif]-->
                    </td>
                </tr>
                <tr>
                    <td class="innerpadding borderbottom">
                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr class="emailRow">
                                <p>AFFILIATE NAME HERE</p>
                            </tr>
                            <tr class="emailRow">
                                <p>Our Records indicate that your policy is up for renewal in 30 days. Please provide the updated proof of insurance to the Director of Operations by email: <a href="mailto:[email protected]">[email protected]</a>.  We appreciate your compliance. </p>
                                <p>Thank you,</p>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</body>
</html>

This is where I put the Enable Scheduling annotation: in my main.java file

@EntityScan(
		basePackageClasses = {ODbApplication.class, Jsr310JpaConverters.class}
)
@EnableScheduling
@SpringBootApplication
@Configuration
public class ODbApplication extends SpringBootServletInitializer {
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(ODbApplication.class);
	}


	public static void main(String[] args) {
		SpringApplication.run(ODbApplication.class, args);
	}

	@Bean
	public FilterRegistrationBean securityDatabaseFilterRegistration(SecurityDatabaseFilter securityDatabaseFilter) {
		FilterRegistrationBean registrationBean = new FilterRegistrationBean(securityDatabaseFilter);
		registrationBean.setEnabled(false);
		return registrationBean;
	}

}

Upvotes: 1

Views: 5571

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 39978

Understand the cron expression, it consists of six fields. <year> field is optional. docs

<second> <minute> <hour> <day-of-month> <month> <day-of-week> <year>

* means all

? means any

@Scheduled(cron = "0 15 10 15 * ?")

You are cron expression is good and it will start at 10:15 AM of 15th day of every month

Is it right to combine these two methods ?

There is no harm in doing this, if this is not working then you are missing something

@EnableScheduling It will just enables the capability

Enables Spring's scheduled task execution capability

@Scheduled

An annotation that marks a method to be scheduled. Exactly one of the cron(), fixedDelay(), or fixedRate() attributes must be specified.

Upvotes: 1

Related Questions