Reputation: 16724
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
Upvotes: 11
Views: 1217
Reputation: 16724
I got it to work by passing the pdf object directly into the campaign_email method and then assigning an attachment.
Upvotes: 0
Reputation: 625
one quick an easy solution would be fetch the url content using net/http and open-uri, to get the attachment
attachments['free_book.pdf'] = open("http://#{request.host}/letter/#{id}.pdf")
eg:
def campaign_email(contact,email)
subject email.subject
recipients contact.email
attachments['free_book.pdf'] = open("http://#{request.host}/letter/#{id}.pdf")
from 'Me <[email protected]>'
sent_on Date.today
body :email => email
end
or, call the PDF generation inside your mailer controller action
Upvotes: 0
Reputation: 3897
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)
Upvotes: 4