Rails 4.2 邮件添加PDF附件后正文内容丢失问题咨询
问题根因
你遇到的问题有两个核心原因:
- 调用
render_to_string生成PDF时,已经消耗了邮件的模板渲染上下文,Rails默认不会重复渲染同一套模板作为邮件正文 - 为邮件添加附件后,Rails会自动将邮件Content-Type设置为
multipart/mixed,此时需要显式指定正文渲染规则,Rails不会自动补全正文内容
修复方案
在添加附件后,调用mail方法时显式声明要渲染的正文格式即可,修正后的代码如下:
def failed_charge(bill) @monthly_bill = bill @organization = bill.organization @edit_account_url = edit_account_url(organization) I18n.with_locale(organization.locale) do @date = I18n.l Time.now.utc.to_date, format: :medium @display_period = [bill.period_start, bill.period_end] .map { |t| I18n.l(t.to_date, format: :medium).strip } .join(' – ') invoice_content = WickedPdf.new.pdf_from_string( # 渲染PDF时指定formats为pdf,避免和正文的html/text格式冲突 render_to_string(template: 'billing_mailer/failed_charge', formats: [:pdf], layout: false), { margin: {top: 0, bottom: 0, left: 0, right: 0} } ) # 调试用文件写入逻辑可保留 File.open('invoice.pdf', 'wb') do |file| file.write invoice_content end attachments['invoice.pdf'] = invoice_content # 调用mail方法时显式指定正文渲染格式 mail( to: bill.billing_email, bcc: [INVOICES_EMAIL_FULL, SUPPORT_EMAIL_FULL], subject: I18n.t('billing_mailer.subject_failed_charge'), ) do |format| format.html { render 'failed_charge' } format.text { render 'failed_charge' } end end end
可选优化
如果你有单独的PDF专属模板(和邮件正文内容不同),可以把生成PDF时的模板名替换为专属PDF模板,避免渲染冗余内容。
内容的提问来源于stack exchange,提问作者Elvin Bayramov
相关产品推荐
相关产品推荐

