Arturs
Arturs

Reputation: 1258

Rails 4: Add mail attachment as remote .pdf file

Result which I want to get, is add file, from remote url, which generates already *.pdf file.

My mailer code

def invoice(partner, invoice)
    @invoice = invoice
    attachments["invoice.pdf"] = open("http://127.0.0.1/invoice/#{invoice.id}.pdf").read
    mail :to => partner.email, :subject => "Invoice to partner"
end

But this code returns error:

Invalid argument - http://127.0.0.1/invoice/14.pdf

Upvotes: 3

Views: 7677

Answers (2)

Max Williams
Max Williams

Reputation: 32933

You shouldn't have the server making an http request to itself to render a page! It has all the resources it needs to make the pdf file.

I don't use prawn, i use acts_as_flying_saucer, which is a rails wrapper for the flying_saucer java app, but i suspect it works a similar way: you should probably (if you're not already) use a rails "wrapper" for Prawn - it should give you some methods you can use in your controller to render out a pdf.

In acts_as_flying_saucer, for example, i would make a pdf like this:

render_pdf :template => "path/to/a/template.html.erb", :layout => "flying_saucer.html.erb", :pdf_file => File.basename(temp_filename)

This will build the pdf in my /tmp folder, and i can then attach it to an email if i want, or send it back to the user with send_file or whatever.

A rails wrapper for Prawn will give you a similar command. Have a look at prawnto or prawn-rails, or, if you're already using a rails wrapper gem/plugin, read the api.

Upvotes: 4

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You need pass path to file on your project like this:

def invoice(partner, invoice)
  @invoice = invoice
  attachments["invoice.pdf"] = File.read("path/to/you/file.pdf")
  mail :to => partner.email, :subject => "Invoice to partner"
end

update:
I propose first to create this file and then apply to the letter, because the file when sending encoded in Base64. For example:

class MyMailer < ActionMailer::Base

  def invoice(partner, invoice)
    @invoice = invoice
    add_pdf!
    mail :to => partner.email, :subject => "Invoice to partner"
  end

  private

  def add_pdf!
    file = some_method_what_generate_and_save_pdf
    attachments["invoice.pdf"] = file.read
  end
end

Upvotes: 4

Related Questions