Send Email by Spring batch with variable attachments

It is very simple to send an Email with attachments by Spring batch framework.

Firstly you need 3 beans for handling the email:
– The first bean initializes JavaMail and sets all needed properties

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.yourEmailDomain.de"/>
    <property name="port" value="25"/>
    <property name="username" value="yourUserName"/>
    <property name="password" value="yourPassword"/>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
        </props>
    </property>
</bean>

– The second bean initializes the Tasklet, which calls the Service for sending the mail. It creates the references to the both other beans.

<bean id="sendMailManager">
    <property name="mailSender" ref="mailSender"/>
    <property name="sendMailService" ref="sendMailService"/>
    <property name="senderAddress" value="sender@emailaddress.de"/>
    <property name="recipient" value="recipient@emailaddress.de"/>
    <property name="attachmentFilePath" value="/path/to/attachment/file/"/>
</bean>

 

– The last bean is the Service for sending the email.

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

 

Now these beans can be called by a batchJob.

<batch:job id="sendEmailJob" restartable="false" job-repository="jobRepository">
    <batch:step id="sendEMail">
        <batch:tasklet ref="sendMailManager" />
    </batch:step>
</batch:job>

 

This is all you need on the XML side in the applicationContext.xml.

Now you have to create the needed Java class files wich are cleed by the beans in XML.

The Bean “sendMailService” is a reference to the de.batch.mail.SendMailService class. In the batch job it is called by the Tasklet named “sendMailManager”.

 

package de.batch.mail;

import java.io.File;
import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.annotations.Name;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

/**
* @author carsten.froehlich
*/


@Stateless
@Name("SendMail")
public class SendMailService {

    private static final Log log = LogFactory.getLog(SendMailService.class);
    private JavaMailSender mailSender;
    private String senderAddress;
    private String recipient;
    private String attachmentFilePath;

    // set the fields
    public void setFields(JavaMailSender mailSender, String senderAddress, String recipient, String attachmentFilePath) {

        this.mailSender = mailSender;
        this.senderAddress = senderAddress;
        this.recipient = recipient;
        this.attachmentFilePath = attachmentFilePath;
    }

    public void sendMail() {
        log.debug("send Email started");
        // read directory
        File directory = new File(attachmentFilePath);
        // get file from directory
        final File file = directory.listFiles(FILE_FILTER)[0];

        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
                mimeMessage.setFrom(new InternetAddress(senderAddress));
                mimeMessage.setSubject("Neuer Report");
                // MimeMessagesHelper is needed for the attachment. The Boolean value in
                // constructor is for multipart/data = true
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                helper.addAttachment(file.getName(), new FileSystemResource(file));
                helper.setText("Text in Email Body");
            }
        };
        try {
            this.mailSender.send(preparator);
            log.debug("send Email completed");
        } catch (MailException ex) {
            log.debug("send Email failed", ex);
        }
    }

    public static FileFilter FILE_FILTER = new FileFilter() {
        public boolean accept(File file) {
            return !file.isDirectory();
        }
    };
 }

 

This is the tasklet, which calls the Service:

 

package de.batch.tasklets;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.mail.javamail.JavaMailSender;

import de.mail.SendMailService;

/**
* @author carsten.froehlich
*/


public class SendMailTasklet implements Tasklet {
    private static final Log log = LogFactory.getLog(SendMailTasklet.class);
    private SendMailService sendMailService;
    private JavaMailSender mailSender;
    private String senderAddress;
    private String recipient;
    private String attachmentFilePath;

    public void setMailSender(JavaMailSender mailSender) {
       this.mailSender = mailSender;
    }
    public void setSenderAddress(String senderAddress) {
        this.senderAddress = senderAddress;
    }

    public void setRecipient(String recipient) {
        this.recipient = recipient;
    }

    public void setAttachmentFilePath(String attachmentFilePath) {
        this.attachmentFilePath = attachmentFilePath;
    }

    public void setSendMailService(SendMailService sendMailService) {
        this.sendMailService = sendMailService;
    }

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        log.debug("execute(StepContribution contribution, ChunkContext chunkContext) begin");
        sendMailService.setFields(mailSender, senderAddress, recipient, attachmentFilePath);
        sendMailService.sendMail();
        log.debug("execute(StepContribution contribution, ChunkContext chunkContext) end");
        return RepeatStatus.FINISHED;
    }
}

 

This is somehow all you need for sending emails by spring batch with attachment.

Print Friendly, PDF & Email

Leave a Comment

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*
*