tsure
tsure

Reputation: 315

Email file using grails export plugin

Currently I am using the export plugin to create an excel file on the fly on the server and then sending it to the browser via response.outputstream (done by the export plugin). Instead, what I want it to create the excel file and once done, email it to the user. Assuming I have the email can someone show me some sample code?

I looked into the export plugin code and it looks like it writes to the response output stream. Can I somehow read from this output stream, create a file, not store it to disc and just email it instead?

Upvotes: 4

Views: 996

Answers (2)

Becca Gaspard
Becca Gaspard

Reputation: 1257

You want to use the attach(String fileName, String contentType, InputStreamSource source) method in the Grails Mail DSL. This allows you to do everything in memory without writing a file to disc.

import org.springframework.core.io.ByteArrayResource
...

OutputStream outputStream = new ByteArrayOutputStream()
exportService.export(type, outputStream, objects, fields, labels, formatters, parameters)
InputStreamSource inputStream = new ByteArrayResource(outputStream.bytes)  //copy output stream to input stream

sendMail {
   mutipart true
   to "[email protected]"
   attach "yourfile.txt", "text/plain", inputStream
}

More info here.

Hope that helps!

Upvotes: 2

MKB
MKB

Reputation: 7619

Export plugin can create file in server as well.

File exportOutput = new File("/home/mkb/test.csv")
def exportOutputStream = new FileOutputStream(exportOutput)
exportService.export('csv', exportOutputStream, User.list(), fields, labels, formatters, parameters)

and once you got the file then you can easily email it using grails mail plugin as an attachment.

Upvotes: 4

Related Questions