Email dynamically generated file

Currently, I allow users to select certain parameters and based on them I generate a csv file and push it as a download to users. eg

send_data <generated csv data>, :disposition => 'attachment' :type => 'text/csv' 

Sometimes, when the data becomes too large for calculation, I do not want users to wait until the file is downloaded as a download. I want to send this file as an attachment in an email.

I can send a letter usually. I can send an existing file as an attachment. I do not want to save this file. I want to send it directly to the user.

How to do it?

+6
source share
2 answers

@juanpastas - I did it the way you suggested. But this led to the fact that the file was displayed as text in the body of the message.

This is how it appeared in the letter.

Content-Type: text / csv; encoding = UTF-8; file name = data.csv Content-Transfer-Encoding: 7 bits Content-Disposition: attachment; file name = data.csv Content-ID: xyzxyz [contents of csv file as text]

Then I turned on the message body and it worked.

 mail(to: user.email, subject: 'XYZ', body: 'XYZ') 

This led to the email having a body and subject that I provided, and the file appeared as an attachment.

+7
source

I have not tested this, but this should work:

 class YourMailer < ActionMailer::Base def csv_mail(user, csv_data) attachments['a.csv'] = csv_data mail(to: user.email) end end 

And in your controller:

 YourMailer.csv_mail(user, csv_data).deliver 

See attachments and inline attachments .

+5
source

All Articles