Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

actionmailer - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
  add_template_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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...