//
you're reading...
Java Mail, Spring

Attaching excel or pdf files to a mail using spring framework

Few days back I got a requirement which said that I need to generate and display and excel file to the user . I used  java excel API JExecl which I found out was in fact quite interesting. You can add cells to them , define cell types , cell fonts and other stuffs.So , for creating excel file in java  Jexcel API are decent enough.

Now the second thing which I needed to do was to send the excel file as an attachment in a mail to the user. My existing code used to support the text mail sending part but now I have to attach the excel file to it. I had generated an array of bytes to dispaly in excel file and now I wanted to use this byte array to be sent as an excel attachment.
When I googled I found solutions majorly related to wiring the file on disk as temp.xls and then reading the file , attaching it and then deleting the temp file which was actually I what I was trying to  avoid as I have never done file handling and some how I am bit scared of file I/O APIs.

Since I was using spring framework , we were using mimeMessageHelper for mails. I looked into the API’s and found out that it also supports attachment with mails and that even without using file I/O  I was able to use my array of bytes.
But there were few problems at first due to InputStreamSource class as I never used it before. Moreover, I did not find a single article on internet which described the whole process with a complete working example. So, I had to hop from one place to another on web to finally get to the solution.

I guess its a very general problem which many people would encounter, so I am giving a sample code which I will explain a bit also.

*******************************************************************************

public void sendBulkAttachMentTextEmail(final Collection<String> to, final String from,
final String subject, final String emailText,final byte[] byteArray)
throws MailServiceException {
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {

MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true);

// Get the array to addresses.
Object[] toAddresses = to.toArray();
int noOfRecipients = toAddresses.length;
String[] addressTo = new String[noOfRecipients];
for (int i = 0; i < noOfRecipients; i++) {
addressTo[i] = (String) toAddresses[i];
}

//Set message To address list.
message.setTo(addressTo);
logger.info(“Recipient : ” + addressTo);
//Set email from address.
message.setFrom(from);
logger.info(“Sender : ” + from);
//Set email subject
message.setSubject(subject);
logger.info(“Subject : ” + subject);

//parse the template and replace the variable values.
freeMarkerConfig.clearTemplateCache();
/*Template mailTemplate = freeMarkerConfig.getTemplate(template);
String text = FreeMarkerTemplateUtils
.processTemplateIntoString(mailTemplate, params);*/

logger.info(“Email Content : “);
//Set the email text.
logger.info(emailText);
message.setText(emailText, true);

ByteArrayResource bar = new ByteArrayResource(byteArray);

message.addAttachment(“Report.xls”,bar,”application/vnd.ms-excel “);

}
};

}

**************************************************************************

You must set the boolean to true in MimemessageHelper constructor. It means that you are defining the mail to be multipart.

Now Spring provides different class implementing InputStreamSource . Since I had the array of bytes I created an instance of ByteArrayResource with the argument in constructor as my byte[]. Lastly you need to define the report name and its type while attaching the ByterArrayResource instance and then you can send the mail.

I guess this information may be useful for people looking for this kind of task and if you have any questions you can put in your comments over here and I would revert back.

Thanks

Gaurav Mutreja

Advertisements

About Gaurav Mutreja

Well I think a lot !! Now I would like to speak a bit!

Discussion

5 thoughts on “Attaching excel or pdf files to a mail using spring framework

  1. Hi,
    Thank you for sparing me a lot of work and making me look clever.
    It does help. I appreciate all your effort.

    Posted by nandha | June 1, 2011, 10:20 am
  2. IT was really fast implementation ; Really helped me

    Posted by manish | July 1, 2011, 6:38 pm
  3. great article, it really help me a lot 😀
    you sir save my day 😀

    Posted by snippetjournal | October 17, 2014, 2:05 pm

Trackbacks/Pingbacks

  1. Pingback: Send Multipart/Attachment email Using MimeMessageHelper | snippetjournal - October 17, 2014

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: