11

In my Rails application, I'm trying to attach the invoice to the email:

def invoice(invoice)
  attachment :content_disposition => "attachment",
             :body => InvoicePdf.new(invoice),
             :content_type => "application/pdf",
             :filename => 'invoice.pdf'

  mail(:to => @user.email, :subject => "Your Invoice")
end

The InvoicePdf is a Prawn PDF document:

class InvoicePdf < Prawn::Document
  def initialize(order, view)
    draw_pdf
  end

  def draw_pdf
    # pdf stuff
  end
end

I get no attachments in the email. What am I doing wrong? Any tips would be welcomed and appreciated.

Edit: The Rails version I'm using is 3.0.x

alexs333
  • 12,143
  • 11
  • 51
  • 89

2 Answers2

15

Take a look at the Action Mailer Guide. You need to call the attachments method for you to add an attachment.

Try this:

attachments['attachment_filename'] = InvoicePdf.new(invoice)

This is assuming that calling InvoicePdf.new(invoice) generates a file and returns an IO object representing that file. I also noticed that your InvoicePdf class initializer expects two parameters but you are passing only one.

Update: Also note that Action Mailer will take the file name and work out the mime type, set the Content-Type, Content-Disposition, Content-Transfer-Encoding and base64 encode the contents of the attachment all for you so setting it manually isn't necessary unless you want to override the defaults.

Based on your pdf generation method, this will probably be better:

invoice = InvoicePdf.new(invoice)
attachments["invoice.pdf"] = { :mime_type => 'application/pdf', :content => invoice.render }
mail(:to => @user.email, :subject => "Your Invoice")
Kibet Yegon
  • 2,763
  • 2
  • 25
  • 32
  • Would you know by any chance how to convert PDF object into the IO object? – alexs333 Sep 06 '12 at 07:33
  • 1
    Assuming your InvoicePdf class generates a pdf on the filesystem say your rails tmp directory and returns the file path you'd simply do `attachments['invoice.pdf'] = File.read(InvoicePdf.new(invoice))` – Kibet Yegon Sep 06 '12 at 07:44
  • Yep something like this solves it: `attachments['invoice.pdf'] = File.read(InvoicePdf.new(invoice).render_file("invoice.pdf"))` – alexs333 Sep 06 '12 at 07:51
  • Glad that worked, I also just updated my answer based on your needs. – Kibet Yegon Sep 06 '12 at 07:53
0

Isnt this just

attachments["invoice.pdf"] = InvoicePdf.new(invoice)

since 3.0?

Atastor
  • 741
  • 3
  • 11