ramana reddy
ramana reddy

Reputation: 41

Using spring batch config how to send a mail and how to configure in the job

I need to send a mail using spring batch configs.in the mail having the status of the mail(It's success or failure) now am able to read data from csv and write into the Database.after write into the database i need to send a mail. please any one suggest to me this is my java config file job configuration

return jobs.get("insertIntoDbFromCsvJob")
            .start(readRegistrations())
                .build();
    }

here is am readRegistrations() step is read data from csv and write into the database. now i need to send a mail if that step is succec or failure.

Upvotes: 4

Views: 11655

Answers (1)

ArunM
ArunM

Reputation: 2314

You can use spring email support and job listeners.

    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setHost("localhost");
        javaMailSenderImpl.setUsername("");
        javaMailSenderImpl.setPassword("");
        javaMailSenderImpl.setProtocol("smtp");
        javaMailSenderImpl.setPort(25);
        return javaMailSenderImpl;
    }

    @Bean
    public SimpleMailMessage templateMessage() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo("[email protected]");
        mailMessage.setSubject("Job Status");
        mailMessage.setFrom("[email protected]");
        return mailMessage;
    }

Implement a listener

@Component
public class JobCompletionNotificationListener extends
        JobExecutionListenerSupport {

    private static final Logger log = LoggerFactory
            .getLogger(JobCompletionNotificationListener.class);

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private SimpleMailMessage templateMessage;

    @Override
    public void afterJob(JobExecution jobExecution) {
        if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
            log.info("!!! JOB FINISHED! Time to verify the results");
            SimpleMailMessage mailMessage = new SimpleMailMessage(
                    templateMessage);
            mailMessage.setText("Job Success");
            javaMailSender.send(mailMessage);
        }
    }
}

Job Config

@Autowired
private JobCompletionNotificationListener listener;

@Bean
public Job importUserJob(JobBuilderFactory jobs, Step s1,
        JobExecutionListener listener) {
    return jobs.get("importUserJob").incrementer(new RunIdIncrementer())
            .listener(listener).flow(s1).end().build();
}

Upvotes: 5

Related Questions