简体   繁体   English

如何使用ActionMailer发送HTML电子邮件?

[英]How do I send html emails with ActionMailer?

Using rails 2.3.14 使用rails 2.3.14

my email erb: data.html.erb: 我的电子邮件erb:data.html.erb:

<% @data.each do |error| %>
    <table>
        <% error.each_pair do |k, v| %>
            <tr>
                <td>
                    <%= k %>
                </td>
                <td>
                    <%= ap v %>
                </td>
            </tr>   
        <% end %>
    </table>
    <br />
<% end %>

I can receive the email, but when I do, it displays as plain text -- rather than rendering the HTML. 我可以收到电子邮件,但是当我这样做时,它会显示为纯文本 - 而不是呈现HTML。

Action Mailer config: Action Mailer配置:

config.action_mailer.raise_delivery_errors = true

# Send emails during development
config.action_mailer.perform_deliveries = true
ActionMailer::Base.delivery_method = :sendmail

UPDATE: had to specify the content type in my delivery method: 更新:必须在我的交付方式中指定内容类型:

 def data(data, sent_at = Time.now)
    Time.zone = 'Eastern Time (US & Canada)'

    content_type 'text/html'
    subject     "[#{RAILS_ENV}] An error has occurred - #{Time.now.to_s("%B %d, %Y")}"
    recipients  "bugs@mydomain.com"
    from        AppConfig['from_email']
    sent_on     sent_at
    @body   =   {:data => data}
  end

It seems as though rails may be somehow caching the text template under certain circumstances. 在某些情况下,似乎rails可能以某种方式缓存文本模板。

I just 我只是

  1. Generated a new mailer with a single view, a text view 生成一个具有单个视图,文本视图的新邮件程序
  2. Tested the mailer and sent a text email 测试了邮件并发送了一封短信
  3. Renamed the text email to html (foo.text.haml -> foo.html.haml) 将文本电子邮件重命名为html(foo.text.haml - > foo.html.haml)
  4. Retested the mailer ... and got the text email (boo!) 重新测试邮件...并收到短信(嘘!)
  5. Created an HTML version alongside the text version with a new name (bar.html.haml) 使用新名称(bar.html.haml)在文本版本旁创建HTML版本
  6. Restarted the server 重启服务器
  7. Retested (sending bar). 重新测试(发送栏)。 This time got an HTML email. 这次有一封HTML电子邮件。
  8. Retested the original html email (foo). 重新测试了原始的html电子邮件(foo)。 Got the HTML email 得到了HTML电子邮件

cray. 小龙虾。

使用<%=原始k%>或<%= k.html_safe%>

From d11wtq's comment : 来自d11wtq的评论

Specify the content_type as text/html : content_type指定为text/html

ActionMailer::Base.mail(
  content_type: "text/html",
  from: "sender@example.com",
  to: "your_email@example.com",
  subject: "This is a test",
  body: "<h2>HTML Email Test</h2><p>This is a <b>test</b>.</p>"
).deliver_now

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM