MaxRah
MaxRah

Reputation: 243

How to display images in a Rails mailer email?

I have an app that sends an email when a user signs up. I've got the emails to send successfully but the images are not getting sent. I'm hosting on Heroku and using Sendgrid to send emails.

Here's my signup_email.html.erb view:

<tr>
   <td style="padding: 20px 0; text-align: center">
      <img
         src="<%= Rails.application.config.action_mailer.default_url_options[:host] %>assets/email/logo.png"
            width="200"
            height="50"
            alt="logo"
            border="0"
            style="height: auto; background: #dddddd; font-family: sans-serif; font-size: 15px; line-height: 15px; color: #555555;"
       />
   </td>
</tr>

This is not an issue where the browser hides images by default because I've tested on various browsers and tried to show images. The image path in the email shows: heroku-root/assets/email/logo.png

Here's the signup user_mailer.rb:

class UserMailer < ActionMailer::Base
  default from: "App <[email protected]>"

  def signup_email(user)
    @user = user

    mail(:to => user.email, :subject => "Thank you for joining!")
  end
end

I've precompiled assets with rake assets:precompile so the logo is stored in public/assets/email directory.

The production.rb setting:

# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false

# Generate digests for assets URLs
config.assets.digest = true

config.action_mailer.default_url_options = { :host => ENV['DEFAULT_MAILER_HOST'] }

config.action_mailer.delivery_method = :smtp

config.serve_static_assets = true

I've tried using the inline attachment method from the Rails documentation but emails weren't getting sent at all.

class UserMailer < ActionMailer::Base
  default from: "App <[email protected]>"

  def signup_email(user)
    @user = user
    attachments.inline["logo.png"] = File.read("#{Rails.root}app/assets/email/logo.png")

    mail(:to => user.email, :subject => "Thank you for joining!")
  end
end

In the view, I call the logo like this:

<%= image_tag(attachments['logo.png'].url) %>

With the method above the emails don't get sent at all and I get the error that it couldn't find the file logo.

Upvotes: 0

Views: 4303

Answers (1)

teja rajana
teja rajana

Reputation: 46

You should just be able to use the regular old <%= image_tag("logo.png") %> helpers just like you would use in your views. You may need to set your asset_host so that it includes a full URL for the images in the emails since they aren't displayed in the browser under your domain.

# I believe these should do the trick:
config.action_controller.asset_host = 'http://localhost:3000'
config.action_mailer.asset_host = config.action_controller.asset_host

Upvotes: 1

Related Questions