如何在Rails 2.3.5中将prawnto呈现的.pdf附加到电子邮件中?

时间:2010-10-15 06:57:29

标签: ruby-on-rails email pdf attachment

我的应用程序在通过将其传递给URL(例如,domain.com /letter / 2.pdf)来呈现时创建.pdf文件

不会在任何地方保存。

如何在出站电子邮件中将该实际pdf作为附件。

这是我的邮件:

  def campaign_email(contact,email)
    subject    email.subject
    recipients contact.email
    from       'Me <me@me.com>'
    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

这是创建/呈现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

注意:我硬编码localhost:3000 /如何用变量替换它,以便在dev上它是localhost:3000并且在生产时它是正确的域?有没有办法在此包含路由?)

错误:我得到了

  

参数无效 -   http://localhost:3000/contact_letters/9.pdf

3 个答案:

答案 0 :(得分:5)

以下是rails 2的示例

class ApplicationMailer < ActionMailer::Base
# attachments
def signup_notification(recipient, letter)
  recipients      recipient.email_address_with_name
  subject         "New account information"
  from            "system@example.com"

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

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

在您的视图中或您调用方法的任何地方:

ApplicationMailer.deliver_signup_notification(letter)

答案 1 :(得分:0)

一个快速简单的解决方案是使用net / http和open-uri获取网址内容,以获取附件

attachments['free_book.pdf'] = open("http://#{request.host}/letter/#{id}.pdf")

例如:

def campaign_email(contact,email)
    subject    email.subject
    recipients contact.email
    attachments['free_book.pdf'] = open("http://#{request.host}/letter/#{id}.pdf")
    from       'Me <me@me.com>'
    sent_on    Date.today

    body       :email => email
end

或者,在您的邮件程序控制器操作中调用PDF生成

答案 2 :(得分:0)

我通过将pdf对象直接传递到campaign_email方法然后分配附件来实现它。