Rails将图像嵌入电子邮件中

时间:2014-12-01 20:33:13

标签: ruby-on-rails

在Rails应用程序中,我正在尝试将(内联)图像(徽标)嵌入到电子邮件中。

这是invoice.mailer.rb:

class InvoiceMailer < ActionMailer::Base
  def invoice_email(invoice)
    @invoice = invoice
    @recipients = @invoice.workorder.client.contacts.where(:receiveinvoices => true)
    tomail = @recipients.collect(&:email).join(",")
    frommail = @invoice.tenant.from_email
    copymail = @invoice.tenant.copy_email
    attachments.inline['AME_Logo.gif'] = File.read( Rails.root.join('app/assets/images/AME_Logo.gif') )

    mail(
        :to => tomail,
        :bcc => copymail,
        :from => frommail,
        :subject => "New Invoice from " + @invoice.tenant.name

    )
  end
end

这是_invoice_email.html.erb:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <style type="text/css" media="screen">
  </style>
</head>
<body style="margin-left: auto; margin-right: auto; width: 700px">
<div class="invoice">
<div class="inv_header" style="margin-left:10px; margin-right: auto; width: 650px">
  <h4>Invoice</h4>
  <%= image_tag attachments['AME_Logo.gif'].url -%>
</div>

我从image_tag代码行中收到此错误:

undefined local variable or method `attachments' for #<#<Class:0x007f8a49ce7b08>:0x007f8a4e352110>

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

为什么不直接在image_tag助手中对路径进行硬编码?

<%= image_tag('http://path-to-your-site/assets/AME_Logo.gif') %>

如果它必须是附件,则必须使其成为实例变量:

@attachments.inline['AME_Logo.gif'] = File.read( Rails.root.join('app/assets/images/AME_Logo.gif') )

并在您的邮件中:

<%= image_tag @attachments['AME_Logo.gif'].url -%>