Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 892

Spring Email Scheduling Example Using Quartz Scheduler

$
0
0

In this post we’ll see a Spring email scheduling example using Quartz scheduler integration with Spring framework.

Spring Mail API is used to configure Java mail for sending email.

Spring Quartz integration facilitates the use of Quartz for job scheduling.

Spring email scheduling example using Quartz scheduler

In this Spring email scheduling example reminder mail is sent to a set of Users everyday at the scheduled time. For scheduling the mail to be triggered at the specific time Quartz scheduler is used.

Technologies Used

  • Spring 5.0.8.Release
  • Java 10
  • Java Mail API
  • Quartz Scheduler

Maven Dependencies

You need to add following dependencies for sending mail using Spring framework using Quartz.


<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.8.RELEASE</spring.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring module Required for Quartz integration -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>

Bean class (User.java)


public class User {

private String firstName;
private String lastName;
private String email;

public User() {

}
public User(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

Spring email scheduling example – Quartz Job class

Quartz scheduler job that would be called at the configured time. This class uses the EmailService class for sending the email. Here a dummy list of Users is created and EmailService method is called for each user in the list once the job is triggered.


@Service
public class MailReminderJob extends QuartzJobBean {

private EmailService emailService;
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println("In executeInternal");
List<User> userList = getListOfUsers();
for(User user : userList) {
emailService.sendMail(user);
}
}

// Dummy method for adding List of Users
private List<User> getListOfUsers() {
List<User> users = new ArrayList<User>();
users.add(new User("Jack", "Reacher", "jr@gmail.com"));
users.add(new User("Remington", "Steele", "rs@gmail.com"));
return users;
}
}

Spring email scheduling example – Mail Service class

Class used for sending the mails. This class get the mail properties like From and Subject from a properties file email.properties which is stored in the application’s classpath. MimeMessageHelper is used here so that attachment can also be sent with the email.

EmailService.java


@Service("emailService")
@Configuration
@PropertySource("classpath:email.properties")
public class EmailService {
@Autowired
private Environment env;
@Autowired
private JavaMailSender mailSender;

public void sendMail(User user) {
System.out.println("In Send mail");
try{
MimeMessage message = mailSender.createMimeMessage();
// use the true flag to indicate you need a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(env.getProperty("email.From"));
// each user's email ID
helper.setTo(user.getEmail());
helper.setSubject(env.getProperty("email.Subject"));
helper.setText("Dear " + user.getFirstName() + "" +user.getLastName()
+ "\r\n" + "This is a reminder mail to go through the attached PDF.");
helper.addInline("Inline image", new ClassPathResource("netjs.png"));
helper.addAttachment("MyImage.png", new ClassPathResource("netjs.png"));
helper.addAttachment("MyPdf.pdf", new FileSystemResource("F:\\Doc\\index.pdf"));

this.mailSender.send(message);
}
catch (MessagingException ex) {
// just printing
System.out.println(ex.getMessage());
}
}
}

email.properties


email.To=TO@gmail.com
email.From=FROM@gmail.com
email.Subject=Reminder Mail

Spring email scheduling example – Configuration

The job is configured here to run at 8 AM everyday.

CronTrigger is used here for triggering the job using the implementation CronTriggerFactoryBean provided by the Spring framework for Quartz scheduling.

Trigger is scheduled using a SchedulerFactoryBean that exposes triggers to be set as properties.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="org.netjs.service" />
<!-- Mail related configuration -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com"/>
<property name="port" value="587"/>
<property name="username" value="GMAIL_USER_NAME"/>
<property name="password" value="PASSWORD"/>
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
<!-- Quartz scheduler related configuration -->
<bean name="emailReminderJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="org.netjs.service.MailReminderJob"/>
<property name="jobDataAsMap">
<map>
<entry key="emailService" value-ref="emailService"></entry>
</map>
</property>
</bean>

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="emailReminderJob"/>
<!-- run every morning at 8 AM -->
<property name="cronExpression" value="0 0 8 * * ?"/>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
</beans>

To run this example you can use the following class.


public class App {
public static void main( String[] args ){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");

}
}

That's all for this topic Spring Email Scheduling Example Using Quartz Scheduler. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring MVC Generate Response as JSON Example
  2. Spring Transaction Management JDBC Example Using @Transactional Annotation
  3. Spring Batch Processing Using JDBCTemplate batchUpdate() Method
  4. Spring Example Program Using Automatic Configuration
  5. How to Read Properties File in Spring Framework

You may also like -

>>>Go to Spring Tutorial Page


Viewing all articles
Browse latest Browse all 892

Trending Articles