9.4. Attachments

E-mail attachments are also defined in the controller.
As an example we add in app/mailers/notification.rb the Rails image app/assets/images/rails.png to an e-mail as attachment:
class Notification < ActionMailer::Base
  default from: "from@example.com"

  def new_account(user)
    @user = user
    attachments['rails.png'] = File.read("#{Rails.root}/app/assets/images/rails.png")
    mail(:to => user.email,
         :subject => "The new account #{user.name} is active.")
  end
end

Inline Attachments

For inline attachments in HTML e-mails, you need to use the method inline when calling attachments. In our example controller app/mailers/notification.rb:
class Notification < ActionMailer::Base
  default from: "from@example.com"

  def new_account(user)
    @user = user
    attachments.inline['rails.png'] = File.read("#{Rails.root}/app/assets/images/rails.png")
    mail(:to => user.email,
         :subject => "The new account #{user.name} is active.")
  end
end
In the HTML e-mail, you can access the hash attachments[] via image_tag. In our example the app/views/notification/new_account.html.erb would look like this:
<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
  </head>
  <body>
    <%= image_tag attachments['rails.png'].url, :alt => 'Rails Logo' %>
    <p>Hello <%= @user.name %>,</p>

    <p>your new account is active.</p>

    <p><i>Have a great day!</i></p>
    <p>A Robot</p>
  </body>
</html>

Updates about this book will be published on my Twitter feed.