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

11

当我的应用程序通过将其传递到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/,如何使用变量代替它,以便在开发环境下为localhost:3000,在生产环境下为正确的域名?是否可以包含路由规则?

错误:出现无效参数 - http://localhost:3000/contact_letters/9.pdf


你用的是 Rails 2 还是 3? - pizza247
你能否展示一下发送PDF的信件控制器中的代码? - nathanvda
是的,我可以展示控制器,在上面进行编辑。 - Satchel
你用什么来创建PDF文件?是PDFKit吗?也许展示生成文件的代码会有所帮助。 - x0rist
我正在使用Prawn来生成它。 - Satchel
3个回答

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)

那个,或者你正在使用的创建PDF的方法 - pizza247
然后将信件传递给ActionMailer:我对我的回复进行了编辑。 - pizza247
所以在使用signup_notificaiton之前,我使用letter = contact_letter_path(@contact_letter, :format => 'pdf" -- 这将在信函对象中存储pdf,并可以作为附件添加? - Satchel
为什么deliver_signup_notification(letter)只传递letter参数,而不传递recipient参数,尽管signup_notification需要两个参数? - Satchel
这似乎不起作用...看起来需要一个打开文件命令... - Satchel
显示剩余3条评论

0

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

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生成


如何在邮件控制器动作中调用PDF生成?我可以使用吗? - Satchel
attachments['free.pdf'] = open(contact_letter_path(@contact_letter, :format => 'pdf')) - Satchel

0

我通过直接将pdf对象传递到campaign_email方法中并分配附件来使其工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接