Search code examples
ruby-on-railsruby-on-rails-5actionmailerrake-task

images not showing up in rask task with action mailer on Rails


So I created a welcome email for my users. I want this email to be sent at a specific time so I nest it into a rake task and add it to my heroku scheduler.

The thing is, the email template has images.

When I open the console and type UserMailer.welcome_email(user).deliver_now, everything work fine. Images do show up when I receive the email.

However, when I run rake send_welcome_email, the email get sent but none of the images show up inside.

Here is my user_mailer.rb:

  def welcome_email(user)
    @user = user
    mail(to: @user.email, subject: 'Welcome !')
  end

my scheduler.rake:

desc "This task is called by the Heroku scheduler add-on. It aims to send the second of the four welcome emails to new users"
task :send_welcome_email => :environment do
  users = User.find_by(email: "[email protected]")
  puts 'Sending welcome email...'
    UserMailer.welcome_email(users).deliver_now
  puts '...Done !'
end

and my image_tags in my welcome_email.html.erb:

<%= image_tag "myimage.svg" %>
<%= image_tag "email_images/myotherimage.jpg" %>

Notice that I have already tried to change the relative path like so:

  • /myimage.svg
  • /images/myimage.svg
  • /assets/images/myimage.svg
  • images/myimage.svg
  • assets/images/myimage.svg

where could the problem come from ?


Solution

  • What you can do is explicitly state which images you want in the mailer (UserMailer), like

    attachments.inline['myimage.svg'] = File.read("#{Rails.root.to_s + '/app/assets/images/myimage.svg'}")
    

    From there, you can call it in the mailer template with

    <%= image_tag attachments.inline["myimage.svg"].url %>