Pavel
Pavel

Reputation: 1974

Rails Action Mailer: images in emails

I'm trying to paste images into email. The problem is emails comming without images inside

development.rb

  config.action_mailer.default_url_options = {
    :host => 'localhost:3000',
    :only_path => false
  }
  config.action_mailer.raise_delivery_errors = false
  config.action_mailer.asset_host = 'http://localhost:3000'

view file:

<div class="image">
  <%= image_tag image_path('email-logo.png') %>
</div>

Where did I make a mistake? Please ask if you need more information.

Upvotes: 30

Views: 27151

Answers (5)

Giacomo
Giacomo

Reputation: 1

I am not a rails guru, but I found this one:

  1. put your image email-logo.png inside public folder of rails project;
  2. in your email (ex. views/devise/mailer/my_email.html.erb, set the image tag like this:

    <%= image_tag("http://#{ActionMailer::Base.default_url_options[:host]}:#{ActionMailer::Base.default_url_options[:port]}/email-logo.png") %>
    

Upvotes: -3

VoidZero
VoidZero

Reputation: 550

I agree with Utsav Kesharwani. I recently faced the same problem. As the localhost is not publicly available, you cannot access images of localhost.

So, One practical solution to this problem can be to upload your images to cloud and accessing them when you want to display those images.

I personally prefer Cloudinary -- A cloud-based service that provides an end-to-end image management solution including uploads, storage, manipulations, optimizations and delivery.

You can refer to Cloudinary documentation for rails: http://cloudinary.com/documentation/rails_integration#getting_started_guide

I hope this helps.

Upvotes: 0

Utsav Kesharwani
Utsav Kesharwani

Reputation: 1745

You're sending emails from localhost:3000, which isn't publicly available (and limited to your machine only).

You have to expose your local environment, so that images can be downloaded in your mail client.

Use service like ngrok to expose your local domain.

Once done, be sure to replace config.action_mailer.asset_host = 'http://localhost:3000'

with the ngrok URL (something like config.action_mailer.asset_host = 'http://<xxx>.ngrok.com')

Also, in your view file, you'll have to ensure that you specify the absolute url for the image (and not just the relative path). You can read more on that here: How do I get an absolute URL for an asset in Rails 3.1?

Upvotes: 16

a14m
a14m

Reputation: 8055

try

<div class="image">
  <%= image_tag('email-logo.png') %>
</div>

Make sure you set config.action_controller.asset_host and config.action_mailer.asset_host

Upvotes: 30

oxtub
oxtub

Reputation: 199

If you use the

image_url('e-mail-logo.png')

instead of

image_path()

it will render the absolute path to the image, which should work. The internal path to the image is meaningless in the context of the message.

Upvotes: 4

Related Questions