Sending Emails with ActionMailer in Ruby on Rails 6: Part 1

Thomas Dubiel
2 min readMar 13, 2021

Sending emails in Rails is quite simple and intuitive thanks to ActionMailer. In this 2 part tutorial, we will cover how to send emails in Rails 6 using ActionMailer and Sendgrid. In part 1, we will cover how to set up mailers for user account sign up notification. In part 2, we will configure Sendgrid in order to send emails in a production environment.

Mailers in Rails function very similarly to controllers. When we generate a mailer we create associated views as well. We can also utilize instance variables that are accessible in the views, where views for mailers are identical to the traditional mailers we are used to. A mailer can be generated in the following way:

$ bin/rails generate mailer UserSignupMailer
create app/mailers/user_signup_mailer.rb
create app/mailers/application_mailer.rb
invoke erb
create app/views/user_signup_mailer
create app/views/layouts/mailer.text.erb
create app/views/layouts/mailer.html.erb
invoke test_unit
create test/mailers/user_signup_mailer_test.rb
create test/mailers/previews/user_signup_mailer_preview.rb
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default from: "from@example.com"
layout 'mailer'
end
# app/mailers/user_signup_mailer.rb
class UserSignupMailer < ApplicationMailer
end

This command generates the mailer, associated views and some test files. In this case, we will be sending confirmation emails when a user account gets created in our application, which means that along with editing our user_signup_mailer.rb file, we will need to edit our users_controller.rb file to send an email confirmation when a user account gets created, like so:

And a simple mailer:

The method send_signup_email(user) is what we call on the UserSignupMailer class in the users controller when a new user gets created. At this point, when we create a new user, a real email will not be sent because we have not pushed our code to production or configured our email service provider(which we will do in part 2 of this tutorial with Sendgrid). However, we can confirm that our code is working by creating a new user in the development environment and checking the rails console to see if an email will be sent. Your rails console output should be similar to the following:

In part 2 of this tutorial, we will push our application to production and configure Sendgrid to send emails when user accounts get created. There will be many complicated steps in part 2, however, we can see that ActionMailer provides a very streamlined way to send emails in the development environment.

--

--