Beliebte Suchanfragen

Cloud Native

DevOps

IT-Security

Agile Methoden

Java

|
//

Email sending with Spring Batch

6.9.2011 | 3 minutes of reading time

Like in the last post (Send data secure with sftp and Spring Batch ) this post is handling a not very new but also very important technology. It shows, how sending emails can be handled easily with Spring Batch. This framework has some ready components, which only must be combined.

In the following example three beans are declared, which are needed for sending emails:

  • The JavaMail Bean and set all needed parameters
  • The Tasklet Bean, which calls the service for sending the mail. This bean is the central bean and reference both other beans.
  • The Service bean

The Java Mail Bean

1<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
2    <property name="host" value="smtp.yourEmailDomain.de"/>
3    <property name="port" value="25"/>
4    <property name="username" value="yourUserName"/>
5    <property name="password" value="yourPassword"/>
6    <property name="javaMailProperties">
7        <props>
8            <prop key="mail.smtp.auth">true</prop>
9        </props>
10    </property>
11</bean>

The Tasklet Bean

1<bean id="sendMailManager">
2    <property name="mailSender" ref="mailSender"/>
3    <property name="sendMailService" ref="sendMailService"/>
4    <property name="senderAddress" value="sender@emailaddress.de"/>
5    <property name="recipient" value="recipient@emailaddress.de"/>
6    <property name="attachmentFilePath" value="/path/to/attachment/file/"/>
7</bean>

The Service Bean

1<bean id="sendMailService" class="de.batch.mail.SendMailService" />

Now these three beans can be called by a BatchJob.

1<batch:job id="sendMailJob" restartable="false">
2  <batch:step id="sendMailStep">
3    <batch:tasklet ref="sendMailManager" />
4  </batch:step>
5</batch:job>

Now you have to create the needed Java class files wich are called by the beans in XML. The Bean “sendMailService” is a reference to the de.batch.mail.SendMailService class. In the BatchJob it is called by the Tasklet named “sendMailManager”.

1package de.batch.mail;
2 
3import java.io.File;
4import javax.ejb.Stateless;
5import javax.mail.Message;
6import javax.mail.internet.InternetAddress;
7import javax.mail.internet.MimeMessage;
8 
9import org.apache.commons.logging.Log;
10import org.apache.commons.logging.LogFactory;
11import org.jboss.seam.annotations.Name;
12import org.springframework.core.io.FileSystemResource;
13import org.springframework.mail.MailException;
14import org.springframework.mail.javamail.JavaMailSender;
15import org.springframework.mail.javamail.MimeMessageHelper;
16import org.springframework.mail.javamail.MimeMessagePreparator;
17 
18@Stateless
19@Name("SendMail")
20public class SendMailService {
21 
22    private static final Log log = LogFactory.getLog(SendMailService.class);
23    private JavaMailSender mailSender;
24    private String senderAddress;
25    private String recipient;
26    private String attachmentFilePath;
27 
28    // set the fields
29    public void setFields(JavaMailSender mailSender, String senderAddress, String recipient, String attachmentFilePath) {
30 
31        this.mailSender = mailSender;
32        this.senderAddress = senderAddress;
33        this.recipient = recipient;
34        this.attachmentFilePath = attachmentFilePath;
35    }
36 
37    public void sendMail() {
38        log.debug("send Email started");
39        // read directory
40        File directory = new File(attachmentFilePath);
41        // get file from directory
42        final File file = directory.listFiles(FILE_FILTER)[0];
43 
44        MimeMessagePreparator preparator = new MimeMessagePreparator() {
45            public void prepare(MimeMessage mimeMessage) throws Exception {
46                mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
47                mimeMessage.setFrom(new InternetAddress(senderAddress));
48                mimeMessage.setSubject("Neuer Report");
49                // MimeMessagesHelper is needed for the attachment. The Boolean value in
50                // constructor is for multipart/data = true
51                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
52                helper.addAttachment(file.getName(), new FileSystemResource(file));
53                helper.setText("Text in Email Body");
54            }
55        };
56        try {
57            this.mailSender.send(preparator);
58            log.debug("send Email completed");
59        } catch (MailException ex) {
60            log.debug("send Email failed", ex);
61        }
62    }
63 
64    public static FileFilter FILE_FILTER = new FileFilter() {
65        public boolean accept(File file) {
66            return !file.isDirectory();
67        }
68    };
69 }

This is the tasklet, which calls the Service:

1package de.batch.tasklets;
2 
3import org.apache.commons.logging.Log;
4import org.apache.commons.logging.LogFactory;
5import org.springframework.batch.core.StepContribution;
6import org.springframework.batch.core.scope.context.ChunkContext;
7import org.springframework.batch.core.step.tasklet.Tasklet;
8import org.springframework.batch.repeat.RepeatStatus;
9import org.springframework.mail.javamail.JavaMailSender;
10 
11import de.batch.mail.SendMailService;
12 
13public class SendMailTasklet implements Tasklet {
14    private static final Log log = LogFactory.getLog(SendMailTasklet.class);
15    private SendMailService sendMailService;
16    private JavaMailSender mailSender;
17    private String senderAddress;
18    private String recipient;
19    private String attachmentFilePath;
20 
21    public void setMailSender(JavaMailSender mailSender) {
22       this.mailSender = mailSender;
23    }
24    public void setSenderAddress(String senderAddress) {
25        this.senderAddress = senderAddress;
26    }
27 
28    public void setRecipient(String recipient) {
29        this.recipient = recipient;
30    }
31 
32    public void setAttachmentFilePath(String attachmentFilePath) {
33        this.attachmentFilePath = attachmentFilePath;
34    }
35 
36    public void setSendMailService(SendMailService sendMailService) {
37        this.sendMailService = sendMailService;
38    }
39 
40    @Override
41    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
42        log.debug("execute(StepContribution contribution, ChunkContext chunkContext) begin");
43        sendMailService.setFields(mailSender, senderAddress, recipient, attachmentFilePath);
44        sendMailService.sendMail();
45        log.debug("execute(StepContribution contribution, ChunkContext chunkContext) end");
46        return RepeatStatus.FINISHED;
47    }
48}

Now you are able to send emails by your BatchJob with a CronJob.

|

share post

Likes

0

//

Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.