Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Testing, Jobs and Deployment

Mailers and File Uploads with Active Storage

Send email with Action Mailer, preview it, and store uploads with Active Storage: attachments, variants, direct uploads, validation and cloud services. Includes runnable ERB mail and blob-store stand-ins.

Two features show up in almost every real application: sending email (welcome messages, receipts, password resets) and accepting files (avatars, documents, images). Rails has a built-in answer for each, Action Mailer and Active Storage, and both follow the same conventions you already know from controllers and views.

The real classes need Rails, a database and a mail or storage service, so they are read-only here. The runnable examples use plain Ruby and the standard library (ERB, Digest) to show how a mailer view is rendered and how a file store identifies uploaded content.

Action Mailer

A mailer is like a controller whose actions produce emails instead of web pages:

SH
bin/rails generate mailer User welcome password_reset
Ruby
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
  default from: "[email protected]"

  def welcome(user)
    @user = user
    @url  = login_url
    mail(to: @user.email, subject: "Welcome to Example, #{@user.name}")
  end
end
ERB
<%# app/views/user_mailer/welcome.html.erb %>
<h1>Welcome, <%= @user.name %>!</h1>
<p>Sign in here: <%= link_to "Log in", @url %></p>

Always provide a text version too (welcome.text.erb); Rails sends a multipart message with both, and mail clients pick one. Layouts live in app/views/layouts/mailer.html.erb.

Sending:

Ruby
UserMailer.welcome(user).deliver_later   # through Active Job: preferred
UserMailer.welcome(user).deliver_now     # inline: console, tests

Details people trip over:

  • Emails need absolute URLs. Set config.action_mailer.default_url_options = { host: "example.com", protocol: "https" } and use *_url helpers, not *_path.
  • Pass the record or its id to deliver_later; the job loads it fresh when it runs.
  • Attach files with attachments["invoice.pdf"] = File.read(path); inline images with attachments.inline["logo.png"].
  • Delivery is configured per environment: :smtp with your provider's credentials in production, :test in tests (messages collect in ActionMailer::Base.deliveries), and in development tools like Letter Opener or MailHog.
  • Previews let you see emails without sending them: put a class in test/mailers/previews/ and open /rails/mailers.
Ruby
class UserMailerPreview < ActionMailer::Preview
  def welcome
    UserMailer.welcome(User.first)
  end
end

Testing a mailer:

Ruby
test "welcome email" do
  email = UserMailer.welcome(users(:ana))
  assert_emails(1) { email.deliver_now }
  assert_equal ["[email protected]"], email.to
  assert_match "Welcome", email.subject
end

Stand-in: rendering a mail view with ERB

Rails views are ERB templates, and Ruby ships ERB. The stand-in below does what mail(...) does: bind instance variables, render a text and an HTML part, and bundle them into a message.

Ruby Stand-in: a mailer built from ERB templates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice ERB::Util.h turned <script> into &lt;script&gt; in the HTML part. Rails does this automatically for <%= %> in .html.erb, which is why user input in an email stays harmless.

Active Storage

Active Storage attaches files to records without adding columns to your table. Install it once, then declare attachments:

SH
bin/rails active_storage:install
bin/rails db:migrate
Ruby
class User < ApplicationRecord
  has_one_attached :avatar do |attachable|
    attachable.variant :thumb, resize_to_limit: [100, 100]
  end
  has_many_attached :documents
end
ERB
<%= form_with model: @user do |f| %>
  <%= f.file_field :avatar, accept: "image/*" %>
  <%= f.file_field :documents, multiple: true %>
  <%= f.submit %>
<% end %>
Ruby
user.avatar.attach(params[:avatar])           # or io: File.open(...), filename:, content_type:
user.avatar.attached?                         # => true
user.avatar.filename                          # => "me.png"
user.avatar.purge_later                       # delete the file in a job

image_tag user.avatar.variant(:thumb)         # resized copy, made on first request
url_for(user.avatar)                          # redirect URL to the file

Under the hood three tables are used: active_storage_blobs (file metadata and checksum), active_storage_attachments (a polymorphic join to your record) and active_storage_variant_records. The bytes themselves live in a service from config/storage.yml: Disk locally, and S3, Google Cloud Storage or Azure in production, selected with config.active_storage.service.

Validate uploads. Rails does not check type or size for you. Do it in the model, and never trust the browser's content_type alone:

Ruby
validate :avatar_is_small_image

def avatar_is_small_image
  return unless avatar.attached?
  errors.add(:avatar, "must be an image") unless avatar.content_type.in?(%w[image/png image/jpeg image/webp])
  errors.add(:avatar, "must be under 2 MB") if avatar.byte_size > 2.megabytes
end

Never allow SVG or HTML from untrusted users without sanitizing, since they can carry scripts. For large files use direct uploads (direct_upload: true on the field): the browser sends the file straight to the storage service and only submits a signed id to your app, so Rails workers are not tied up.

Stand-in: a content-addressed blob store

Ruby Stand-in: blobs with checksum, type check and size limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which URL helper must emails use?

    An email is read outside your site, so relative paths are useless. Absolute URLs need a host configured.
  2. 2. What is the recommended way to send a mail from a controller?

    deliver_later puts the sending in a background job so the request is not delayed by SMTP.
  3. 3. Where does Active Storage keep file bytes?

    Blobs and attachments tables describe the file; the content lives in the service from storage.yml.
  4. 4. Does Active Storage validate file type and size by default?

    You write your own validations, and should not trust the browser-sent content type alone.

Summary

  • Mailers are controller-like classes with ERB views (HTML and text); use deliver_later, absolute URLs and previews.
  • Active Storage attaches files with has_one_attached / has_many_attached, keeps metadata in blob tables and bytes in a service.
  • Variants make resized copies; direct uploads skip your servers.
  • Validate type and size yourself, and treat uploaded SVG or HTML as dangerous.

Next: Deploying a Rails app