Rails 7. ActionMailer::Preview and Mailcatcher

Ilya Zykin
3 min readJan 28, 2023

--

This week I’ve added to Rails 7. Start Kit functionality related to sending and previewing emails. Release 1.2 is here. Details you can find in the PR.

Rails 7. Start Kit and Mailcatcher

How I did it

Step 1

I wanted to install gem mailcatcher directly to the Rails container in my project.

After some attempts I found that mailcatcher uses some old gems that are not compatible with ruby 3.2.

Obviously I just found a docker container and added it to my project.

  # docker/docker-compose.yml
#
mailcatcher:
image: schickling/mailcatcher
ports:
- 1080:1080

Step 2

Now I should add launching of this new container in my bin/setup

  # Mailcatcher
step_info "Launching Mailcatcher Container"
system('docker compose -f docker/docker-compose.yml up mailcatcher -d')
wait('to launch Mailcatcher Container')

Step 3

Now, when we have mailcatcher we should set up an address of the SMTP service.
For development we should modify: config/environments/development.rb

  config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "mailcatcher",
port: 1025
}

address: “mailcatcher” I use because it is a name of the container in docker/docker-compose.yml

Step 4

It is time to create Rails Mailer and implement our new email letter:

$ rails generate mailer demo

Step 5

In app/mailers/demo_mailer.rb we have to implement our email and default params.

class DemoMailer < ApplicationMailer
default from: 'demo@rails7startkit.com'

# DemoMailer.welcome_email.deliver!
def welcome_email
mail(
to: "test@test.com",
subject: 'Welcome to Rails 7. StartKit'
)
end
end

And letter’s content: app/views/demo_mailer/welcome_email.html.erb

<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Welcome to Rails7. StartKit</h1>
<p>Thanks for using this project!</p>
</body>
</html>

Step 6

Time to check our mailer

We go to rails console

$ rails c

In rails console type

DemoMailer.welcome_email.deliver!
We see that email was sent

Step 7

Checking results in mailcatcher. Address: http://localhost:1080

Mailcatcher

Step 8

Also we can implement default ActionMailer::Preview

Just modify: test/mailers/previews/demo_mailer_preview.rb

# Preview all emails at http://localhost:3000/rails/mailers/demo_mailer
class DemoMailerPreview < ActionMailer::Preview
# Accessible from http://localhost:3000/rails/mailers/demo_mailer/welcome_email
def welcome_email
DemoMailer.welcome_email
end
end

And now we can see the result

ActionMailer::Preview

Thank you for your interest to Rails 7. Start Kit

Star/Subscribe to the project to know about most recent updates.

Happy coding!

--

--

Ilya Zykin
Ilya Zykin

Written by Ilya Zykin

IT coach. React and Rails enthusiast. Passionate programmer, caring husband and pancake baker on Sundays. School teacher of computer studies in the past.

No responses yet