Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to embed image into email using Rails?

What is the right way to embed an image into email using Rails?

like image 368
Alexey Zakharov Avatar asked Feb 07 '11 05:02

Alexey Zakharov


3 Answers

I combined the answer from Oksana with a custom helper approach and got the following to work quite nicely.

app/helpers/email_helper.rb

module EmailHelper
  def email_image_tag(image, **options)
    attachments[image] = File.read(Rails.root.join("app/assets/images/#{image}"))
    image_tag attachments[image].url, **options
  end
end

app/mailers/base_mailer.rb

class BaseMailer < ActionMailer::Base
  helper(EmailHelper)
end

app/mailers/my_mailer.rb

class MyMailer < BaseMailer

  def send_my_mail(email)  
    mail to: email, subject: "My Subject"
  end
end

Then for example where I want to attach the company logo in my email layout file I would use

app/views/layouts/email.html.erb

<%= email_image_tag("company_logo.png") %>


Note the **options makes the tag more extensible but it will only work in ruby >=2. To make this work in ruby < 2 you will have to use the older way of handling key word options.


Update 03/25/2022: Rails 6 no longer supports add_template_helper, and now replaces it with helper, as explained by this answer that links to the commit that did so.

like image 172
Tyrone Wilson Avatar answered Nov 19 '22 19:11

Tyrone Wilson


RAILS 5

In your mail method add your inline attachment pointing to your image:

class ConfirmationMailer < ActionMailer::Base
  def confirmation_email
      attachments.inline["logo.png"] = File.read("#{Rails.root}/app/assets/images/logo.png")
      mail(to: email, subject: 'test subject')
  end
end

Then in your mail html view an image_tag with the attachment url:

<%= image_tag(attachments['logo.png'].url) %>
like image 31
Joel Avatar answered Nov 19 '22 18:11

Joel


Adding onto Oksana and tdubs' answers

The module tdubs wrote works on desktop, but for the mobile gmail client, the images appeared as attachments. To fix this, do this for the

app/helpers/email_helper.rb

module EmailHelper
    def email_image_tag(image, **options)
        attachments[image] = {
            :data => File.read(Rails.root.join("app/assets/images/emails/#{image}")),
            :mime_type => "image/png",
            :encoding => "base64"
        }
        image_tag attachments[image].url, **options
    end
end

For the rest, follow tdubs's answer.

like image 23
Pavan Katepalli Avatar answered Nov 19 '22 19:11

Pavan Katepalli