Sending Emails through Rails Apps

After gaining an understanding of the types of Multi-factor Authentication last week(link to the blog post here), I was looking forward to implementing MFA into some of my previous projects to enhance the level of security. A personal email account that only the user would have access to is considered as a possession factor, combining a password and an encrypted soft token sent to a personal email address sounds like a great start. Let’s start by setting up the backend so it’s able to send an email when a user is created in the database.

This blog post serves as notes for my future self and others who may want to implement an emailing functionality for their Rails app through a Gmail account.

Rails is shipped with a handy emails delivery tool known as Action Mailer. Action Mailer allows you to send emails from your application using mailer classes and views(as an email template). If you’re familiar with Rails’ MVC architecture, a mailer is similar to a controller.

They inherit from ActionMailer::Base and live in app/mailers. Mailers also work very similarly to controllers. Some examples of similarities are enumerated below. Mailers have:

Actions, and also, associated views that appear in app/views.

Instance variables that are accessible in views.

The ability to utilise layouts and partials.

The ability to access a params hash.

Setup

Since a valid email address is the only concern at hand, I only created a user table with one column for storing email addresses. A database already has users’ email addresses would also suffice.

Now let’s generate the necessary files for Action Mailer to perform by typing the following command in the console.

rails g mailer <MailerName>

Configuration

To wire up Rails with Gmail, we need to set an SMTP(Simple Mail Transfer Protocol) configuration in config/environments/development.rb for the development build, config/environments/production.rb for production respectively.

config.action_mailer.delivery_method = :smtpconfig.action_mailer.smtp_settings = {
address: ‘smtp.gmail.com’,
port: 587,
domain: ‘example.com’,
user_name: ENV[“EMAIL_USERNAME”],
password: ENV[“EMAIL_PASSWORD”],
authentication: ‘plain’,
enable_starttls_auto: true }

User_name and password are pointing to the email address and password for the Gmail account that you’re wiring up with. Here I used environment variables for these attributes for the obvious reason, clap for this post if you would like me to make a post about a simple way to use environment variables in the future. I also set the config.action_mailer.raise_delivery_errors to true. Rails would simply ignore email delivery errors otherwise.

You would also need to set the Gmail account’s setting here to allow SMTP requests to go through from our app.

As of July 15, 2014, Google increased its security measures and now blocks attempts from apps it deems less secure. You can change your Gmail settings here to allow the attempts. If your Gmail account has 2-factor authentication enabled, then you will need to set an app password and use that instead of your regular password. Alternatively, you can use another ESP to send email by replacing ‘smtp.gmail.com’ above with the address of your provider.

Methods

Our mailers reside in app/mailers/ after being generated. We can write some methods to manage the behavior of the mailer. In my own study project, I just wanted to be able to send an email with quotes from Yoda generated by Faker gem to an email address that was entered by the user.

mail() is the method for sending the actual email message, we are passing the :to and :subject headers to indicate recipient and email subjectline.

In app/views/user_mailer folder, create two files that share the same name as the mailer’s instance method with html.erb and text.erb extension respectively. These are your template files Action Mailer would render as the body of the outbound email when calling the method with the same name.

Now it would be determined by your design at which life cycle during the application should a user should get an email. I decided on when a user was created in the database so I called the mailer method in the create action in my user controller. Note that although the email templates are not a view to be seen, it would still have access to all of the information from an instance variable. You can easily plug the user’s first name, last name into the email. At this point, you should be able to send an email through your Rails application if the routes are mapped correctly.

Conclusion

Having the ability to send out an email from the application is the first step in the attempt of building an MFA system. In the upcoming weeks, I’m gonna look into inserting a salted token into URL and server-side decryption and how that can work into this project. Stay tuned!

You can find me here,

LinkedIn, Github

--

--

--

Software Engineer, React.js || Javascript || RoR

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Enclave Games in 2020, and plans for 2021

Pseudocode, logic in plain English

Red Hat Linux Pinging with Google but not Facebook. Arth Task-13

Certified Kubernetes Administrator Recap

Managing Java Heap size in Kubernetes

Vulnhub-Alfa

Just a tad bit of Java

WWDC 2020 Keynote & Platforms State of The Union: A Developer’s Review

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pan Li

Pan Li

Software Engineer, React.js || Javascript || RoR

More from Medium

What I’ve learned from making a URL shortener

Tasker, React/Redux + Rails API Final Project

Sinatra: Simple Backend Development and You

Ruby:Many to Many Associations