Action Mailer – Send emails from your App Rails

The difference between a transactional mail and marketing

Mail marketing is sent to several people, while transactional mail is sent to only one person. We talk about marketing mail in the case of a newsletter while a confirmation of account creation or an invoice received by mail are transactional mails. The transactional email can be used, for example, to confirm a user’s registration when they have given you their email from a Landing Page.

The SMTP protocol (Simple Mail Tranfert Protocol)

It is a communication protocol allowing the sending of mail between a server and a client.

Action Mailer – Let’s do it !

Create a new project with the name of your choice, here “app_name” specifying the use of a PostgreSQL database. The scaffold will generate the basic functions of the CRUD (Create Read Update Delete) and serve us for the demo.

$ rails new app_name -d postgresql
$ cd app_name rails g scaffold contact Firstname:string Lastname:string email:string
$ git init git add .
$ git commit -m "First commit"
$ hub create
$ git push origin master rails db:create && rails db:migrate

Generate your first mailer with a single welcome email.

$ rails g mailer ContactMailer welcome

The Welcome method defines a type of mail to be sent available in the associated welcome.html.erb view. You can delete the other welcome.text.erb view because it is rare for messengers to fail to read HTML

If you want to add other parameters to the mail action, see the documentation

Add your email address to the ApplicationMailer to send it instead of ‘[email protected]‘.

#app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
default from: '[email protected]'
layout 'mailer'
end

Modify the welcome.html.erb view as below

#app/views/contact_mailer/welcome.html.erb
<h1>Bonjour <%= @contact.Firstname %> <%= @contact.Lastname %></h1> <p>Bienvenue !</p>
A bientôt <strong>BestCompany</strong>

Mailer Action: How to preview the mail ?

Create the previews folder and the contact_mailer_preview.rb file

$ mkdir -p test/mailers/previews && touch test/mailers/previews/contact_mailer_preview.rb

Add the code as below :

The welcome method will retrieve the last contact registered in the database and build the mail

#test/mailers/previews/
contact_mailer_preview.rb
class ContactMailerPreview < ActionMailer::Preview
def welcome
contact = Contact.last
ContactMailer.welcome(contact)
end
end

Create a user from the rail console with the rails c command

$ rails c
Running via Spring preloader in process 29874
Loading development environment (Rails 5.0.4)
irb(main):001:0> contact = Contact.new(Firstname: "John", Lastname: "Doe", email: "[email protected]") => #<Contact id: nil, Firstname: "John", Lastname: "Doe", email: "[email protected]", created_at: nil, updated_at: nil>
irb(main):002:0> contact.save
(0.2ms) BEGIN
SQL (0.4ms) INSERT INTO "contacts" ("Firstname", "Lastname", "email", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["Firstname", "John"], ["Lastname", "Doe"], ["email", "[email protected]"], ["created_at", "2017-06-27 13:37:31.756382"], ["updated_at", "2017-06-27 13:37:31.756382"]]
(5.0ms) COMMIT
=> true
irb(main):003:0> exit

Start your server with rails s and view the mail by entering the following URL : localhost:3000/rails/mailers/contact_mailer/welcome

action mailer preview mail

Action Mailer : Simulate sending emails in development mode

Add the Gem letter_opener in your Gemfile only for the development part.

# Gemfile 
gem "letter_opener", group: :development

Install the Gem using the bundle.

$ bundle install 

Add at the end of your development.rb file the following line :

# config/environments/development.rb
config.action_mailer.delivery_method = :letter_opener

Action Mailer : How to send the mail once the user is created in the database?

First method : From the Contact model

# app/models/contact.rb
class Contact < ApplicationRecord
after_create :send_welcome_email

private
def send_welcome_email
ContactMailer.welcome(self).deliver.now
end
end

Restart your server Rails “rails s” to take into account the changes

Create a user “railsc” and you will automatically see the letter_opener email preview page appear on your browser

Second method : From the Contact controller

As soon as the contact is saved in the database the email is sent

# app/controllers/contact_controller.rb
class ContactsController < ApplicationController
[...]
def create
@contact = Contact.new(contact_params)
if @contact.save
ContactMailer.welcome(@contact).deliver_now
else
render "index.html.erb"
end
end
[...]

Add the index page to your routes.rb

# app/config/locales/routes.rb 
Rails.application.routes.draw do
root "contacts#index"
resources :contacts
end

Now fill in your form from your App with first name, last name and email

action mailer - create new contact

Complete the form and click on Create Contact.

action mailer - form
action mailer letter_opener

You should see a window automatically open that displays the mail to be previewed

mail to preview works

From now on, let’s get down to business! Let’s really send our transactional email

Action Mailer : Send emails for REAL in production

Creation of the repository on the Heroku cloud hosting service

We add “–region eu” so that the server is geographically close to us

“Heroku push origin master” allows you to upload our Git repository to Heroku, “Heroku run rails db:migrate” allows you to migrate the database to Heroku and finally “Heroku open” opens a new window in your browser to display the result

$ heroku create tutomailler --region eu
$ git push heroku master
$ heroku run rails
$ db:migrate
$ heroku open

Using the Postmark service with your own domain

We will now add Postmark which manages the SMTP

Start by creating an account on the Postmark service

Create your Postmark server until you confirm your email address.

action mailer Postmark create a new server

Copy the Server API Tokens.

$ heroku config:set POSTMARK_API_KEY="4847d3c1-*********************" 

Add the Gem Postmark.

# Gemfile
gem 'postmark-rails'

Install the postmark-railsGem.

$ bundle install 

Configure Postmark for production

N’oubliez pas de changer “yourapp.herokuapp.com” avec le l’URL que vous avez chez Heroku

# config/environments/production.rb
# [...]
config.action_mailer.delivery_method = :postmark
config.action_mailer.postmark_settings = { api_key: ENV['POSTMARK_API_KEY'] }
config.action_mailer.default_url_options = { host: "yourapp.herokuapp.com" }
end

Add DKIM and SPF to your domain

These protocols are used to ensure that emails sent to recipients do not arrive in the SPAM of their Mailbox.

Validate DNS records with your host

Push your code to Github.

$ git checkout -b send_transactional_email
$ git add . git commit -m "send transactional email"
$ git push origin send_transactional_email
$ hub pull-request -m "send transactional email"

From your Github account, click on Merge pull request then on Confirm Merge.

pull-request at Heroku

Get the version of your Github code and send it all to Heroku.

$ git checkout master
$ git pull origin master
$ git push heroku master
$ heroku open

The command heroku open opens a new window of your App at heroku

Create a new contact to test the sending of our welcome email.

heroku app create new contact

The result

action mailer result
transactional mail works
signature Pierre-Christophe

No Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.