NullVoxPopuli
NullVoxPopuli

Reputation: 65183

How do I send html emails with ActionMailer?

Using rails 2.3.14

my email 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.

Action Mailer config:

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  "[email protected]"
    from        AppConfig['from_email']
    sent_on     sent_at
    @body   =   {:data => data}
  end

Upvotes: 6

Views: 7540

Answers (3)

Dan Bechard
Dan Bechard

Reputation: 5291

From d11wtq's comment:

Specify the content_type as text/html:

ActionMailer::Base.mail(
  content_type: "text/html",
  from: "[email protected]",
  to: "[email protected]",
  subject: "This is a test",
  body: "<h2>HTML Email Test</h2><p>This is a <b>test</b>.</p>"
).deliver_now

Upvotes: 7

Caleb
Caleb

Reputation: 3802

It seems as though rails may be somehow caching the text template under certain circumstances.

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)
  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)
  6. Restarted the server
  7. Retested (sending bar). This time got an HTML email.
  8. Retested the original html email (foo). Got the HTML email

cray.

Upvotes: 1

Erick Eduardo Garcia
Erick Eduardo Garcia

Reputation: 1157

use <%=raw k %> or <%= k.html_safe %>

Upvotes: 1

Related Questions