Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send dynamically generated file as email

I am currently allowing users to select certain parameters and based on those, I generate a csv file and push it as a download to the users. e.g.

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

Sometimes as the data becomes too large to compute, I do not want to make the users wait for the file to be pushed as download. I want to send this file as an attachment in an email.

I can send an email normally. I can send an already present file as an attachment. I do not want to save this file. I want to email it directly to the user.

How do I do that?

like image 935
gandalf_grey Avatar asked May 05 '14 03:05

gandalf_grey


2 Answers

@juanpastas - I did it the way you suggested. But that caused the file to be in displayed as a text in the email body.

This is how it appeared in the email.

Content-Type: text/csv; charset=UTF-8; filename=data.csv Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename=data.csv Content-ID: xyzxyz [content of the csv file as text]

Then I included the message body and it worked.

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

This caused the email to have the body and subject I provided and the file appeared as an attachment instead.

like image 88
gandalf_grey Avatar answered Oct 19 '22 23:10

gandalf_grey


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.

like image 30
sites Avatar answered Oct 19 '22 22:10

sites