Email Security with Inline Attachments in Rails

It’s common when adding images to an email to use the image_tag function like this:

1
<%= image_tag(@profile.picture, alt: "#{@profile.username} profile picture") %>

These lines of code generate <img> tags with the src attribute pointing to the image hosted on the Rails server or its object storage. Such images are often referred to as “external images” or “remote content”. While this approach serves most needs adequately, using inline email attachments can provide improvements in privacy, resilience, and security.

Inline attachments offer several advantages, including enhanced privacy by preventing external image fetching, thereby safeguarding user information and eliminating the need for users to enable external images for message comprehension. Additionally, they bolster security and preserve reputation by mitigating risks such as domain takeovers, which could replace images with malicious content. Furthermore, inline attachments ensure accessibility by including alt text with images, thus enhancing user experience without compromising privacy or security.

Using Inline Attachments in a Method:

To incorporate inline attachments into an Action Mailer method, follow these steps:

Read the file from storage within the mailer method:

1
2
3
4
5
6
7
class BillingMailer < ApplicationMailer
  def contract
    # Other email content...
    attachments.inline['profile_picture.png'] = @profile.picture.open(&:read)
    # More email content...
  end
end

Once the image is attached, display it in the email view using the appropriate tag:

1
<%= image_tag(attachments['profile_picture.png'].url), alt: "#{@profile.username} avatar" %>

This methodology ensures that images are embedded directly within the email message, offering advantages in privacy, resilience, and security over externally hosted images.