2

I am generating a xls using 'to_xls' gem. So I have like:

my_xls = User.all.to_xls

Now I want to send it using ActionMailer, I tried like that:

attachments[my_xls.original_filename] =  {
   :content=>my_xls.read, 
   :mime_type=>my_xls.content_type
}

But for my surprise, my_xls is not a file but a String. I guess I could solve that by opening a new file and writing the string to it, but I'm using Heroku and it doesn't like writing to file (Permission denied). The best solution would be generate a file-like stream data (like getting a file from a HTML form) and send it.

I need something like rails send_data controller method, that send a stream of data to the view without generating a new file.

So, how do I do that?

Jirico
  • 1,242
  • 1
  • 15
  • 29

2 Answers2

1

Something close to this, I might have gotten the mime type wrong, it's generic in the code below, but the format I use in my rails code for action mailer is as follows:

attachment "application/octet-stream" do |a|
  a.body = my_xls.read
  a.filename = my_xls.original_filename
end

possible types could be:

"application/excel" or "application/vnd.ms-excel" instead of "application/octet-stream"

I have not tested this...

Also if my_xls is a string instead you might have to convert it to bytes before sending it over the wire:

my_xls.bytes.to_a.pack("C*")

there is a SOF topic here talking about this but this is for send_data, but might still apply:

Difficulty with send_data in Ruby on Rails in conjunction with Spreadsheet plug-in

Just trying to point you in a direction that will hopefully help!

Community
  • 1
  • 1
tronmcp
  • 346
  • 1
  • 6
1

The below chunk of code works like a charm. I have tried this, and is in a working application.

def send_excel_report(file_name, emails, subject, email_content, file_path, bcc_emails = [])

    attachments["#{file_name}.xls"] = File.read(file_path)

    mail(to: emails, subject: subject, from: "my_email@gmail.com", bcc: bcc_emails) do |format|
      format.html { render :partial => "users/mail_body"}
    end
  end

FYI: I have used spreadsheet gem to create the excel