Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I attach a prawnto-rendered .pdf to an email in Rails 2.3.5?

My application creates a .pdf file when it is rendered by passing it to the URL (for example, domain.com/letter/2.pdf)

It doesn't get saved anywhere.

How can I make that actual pdf an attachment in an outbound email.

Here is my mailer:

  def campaign_email(contact,email)
    subject    email.subject
    recipients contact.email
    from       'Me <[email protected]>'
    sent_on    Date.today

    attachment = File.read("http://localhost:3000/contact_letters/#{attachment.id}.pdf")

   attachment "application/pdf" do |a|
    a.body = attachment
    a.filename = "Othersheet.pdf" 
   end
 end

This is the controller that creates/renders the PDF:

def create
    @contact_letter = ContactLetter.new(params[:contact_letter])

    @contact = Contact.find_by_id(@contact_letter.contact_id)
    @letter = Letter.find_by_id(@contact_letter.letter_id)

    if @contact_letter.save
      flash[:notice] = "Successfully created contact letter."

      #redirect_to contact_path(@contact_letter.contact_id)
      redirect_to contact_letter_path(@contact_letter, :format => 'pdf')
    else
      render :action => 'new'
    end
  end

NOTE: I hardcoded localhost:3000/ how can I substitute that with a variable so that on dev it is localhost:3000 and on production is it the correct domain? Is there a way to include routing in this?)

ERROR: I get an

Invalid argument - http://localhost:3000/contact_letters/9.pdf

like image 604
Satchel Avatar asked Oct 15 '10 06:10

Satchel


1 Answers

Here's an example for rails 2

class ApplicationMailer < ActionMailer::Base
# attachments
def signup_notification(recipient, letter)
  recipients      recipient.email_address_with_name
  subject         "New account information"
  from            "[email protected]"

  attachment :content_type => "image/jpeg",
    :body => File.read("an-image.jpg")

  attachment "application/pdf" do |a|
    a.body = letter
  end
end
end

in your view or wherever your calling your method:

ApplicationMailer.deliver_signup_notification(letter)
like image 168
thatmiddleway Avatar answered Sep 28 '22 11:09

thatmiddleway