Rails 3 ActionMailer和Wicked_PDF

Dan*_*l D 22 actionmailer ruby-on-rails-3 wicked-pdf

我正在尝试使用ActionMailer和wicked_pdf生成带有渲染PDF附件的电子邮件.

在我的网站上,我已经分别使用了wicked_pdf和actionmailer.我可以使用wicked_pdf在Web应用程序中提供pdf,并可以使用ActionMailer发送邮件,但是我无法将呈现的pdf内容附加到ActionMailer(针对内容进行编辑):

class UserMailer < ActionMailer::Base
  default :from => "webadmin@mydomain.com"

  def generate_pdf(invoice)
    render :pdf => "test.pdf",
     :template => 'invoices/show.pdf.erb',
     :layout => 'pdf.html'
  end

  def email_invoice(invoice)
    @invoice = invoice
    attachments["invoice.pdf"] = {:mime_type => 'application/pdf',
                                  :encoding => 'Base64',
                                  :content => generate_pdf(@invoice)}
    mail :subject => "Your Invoice", :to => invoice.customer.email
  end
end
Run Code Online (Sandbox Code Playgroud)

使用Railscasts 206(Rails 3中的Action Mailer)作为指南,只有在我不尝试添加渲染的附件时,我才能发送包含我所需的丰富内容的电子邮件.

如果我尝试添加附件(如上所示),我会看到一个看起来正确大小的附件,只有附件的名称没有按预期发现,也不能作为pdf读取.除此之外,我的电子邮件内容丢失了......

有没有人在使用Rails 3.0动态渲染PDF时有使用ActionMailer的经验?

提前致谢! - 担

Uni*_*key 30

WickedPDF可以渲染到一个文件,可以附加到电子邮件或保存到文件系统.

上面generate_pdf的方法对你不起作用,因为它是邮件程序上的一个方法,它返回一个邮件对象(不是你想要的PDF)

此外,如果您尝试在方法本身中调用render,则ActionMailer中存在导致消息格式错误的错误

http://chopmode.wordpress.com/2011/03/25/render_to_string-causes-subsequent-mail-rendering-to-fail/

https://rails.lighthouseapp.com/projects/8994/tickets/6623-render_to_string-in-mailer-causes-subsequent-render-to-fail

有两种方法可以使这项工作,

第一个是使用上面第一篇文章中描述的hack:

def email_invoice(invoice)
  @invoice = invoice
  attachments["invoice.pdf"] = WickedPdf.new.pdf_from_string(
    render_to_string(:pdf => "invoice",:template => 'documents/show.pdf.erb')
  )
  self.instance_variable_set(:@lookup_context, nil)
  mail :subject => "Your Invoice", :to => invoice.customer.email
end
Run Code Online (Sandbox Code Playgroud)

或者,您可以在块中设置附件,如下所示:

def email_invoice(invoice)
  @invoice = invoice
  mail(:subject => 'Your Invoice', :to => invoice.customer.email) do |format|
    format.text
    format.pdf do
      attachments['invoice.pdf'] = WickedPdf.new.pdf_from_string(
        render_to_string(:pdf => "invoice",:template => 'documents/show.pdf.erb')
      )
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 在Rails 3.2.2中,第一种方式在没有黑客入侵@lookup_context的情况下工作.第二种方式导致Mail.app,Sparrow和GMail上的重复或丢失附件. (2认同)