How To Send Email In Rails 7?

User Registration and Onboarding— RailsSeries#Episode 01

J3
Jungletronics
13 min readJun 27, 2023

--

Based on: Eric Schwartz’s lessons: 👉️GitHub

In this post:

You will:

Learn how to Send a welcome email
to new users when they sign up,
providing them with important
information about their account;

Learn how to get started sending
email in rails;

Learn all tricks and tips of
this challenge 👌️

Why not to sending email using Rails 7 like we did 3 times in Python?

Send Emails Using Python — Jupyter Notebook
How To Send Gmail In Python
#PurePythonSeries — Episode #01

Automate Your Email Marketing With Python
How To Create An Email Trigger System in Python
#PurePythonSeries — Episode #02

Send Email Using SMTP
Send Mail To Any
Internet Machine (SMTP or ESMTP)

#PurePythonSeries — Episode #11

This is my challenge. I wish you were with us, it’s so much fun.

fig-1. Prerequisite to reproduce this code: Gmail Account and Stamina to learn more.

Hi, Welcome! Let’s get started!

00#step — Create rails app (send_email_rails_7_app); Go to Ubuntu terminal and type:

First, my environment:

ruby -v
ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux]

rails -v
Rails 7.0.5
rails new send_email_rails_7_app
cd send_email_rails_7_app

01#step — Open vs code:

code .

Click on any ruby file to activate Ruby on vs code Terminal.

02#step — Create User resource using scaffold generator:

rails g scaffold User name:string email:string
rails db:migrate

The line rails g scaffold User name:string email:string is a command used in Rails to generate a scaffold for the User model, along with its associated views, controller, and migration.

Breaking down the command:

  • g is short for generate, indicating that you want to generate code.
  • scaffold is the type of generator you want to use. A scaffold generator creates a set of files for a specific model that includes the model itself, its views, controller, and migration.
  • User is the name of the model for which you want to generate the scaffold.
  • name:string email:string are the attributes of the User model. In this case, it specifies that the User model has two attributes: name of type string and email of type string.

When you execute this command in the terminal, Rails will generate several files and directories based on the scaffold:

  1. Migration: A migration file will be created in the db/migrate directory. It contains the necessary instructions to create a corresponding table in the database with columns for the specified attributes (name and email in this case).
  2. Model: A model file (user.rb) will be created in the app/models directory. The model represents the User object and includes validations and associations.
  3. Controller: A controller file (users_controller.rb) will be created in the app/controllers directory. It includes actions like index, show, new, create, edit, update, and destroy that handle the CRUD operations for the User model.
  4. Views: A set of view files will be created in the app/views/users directory. These views include templates for displaying and interacting with User records, such as index.html.erb (listing all users), show.html.erb (displaying a specific user), new.html.erb (rendering the user creation form), and so on.

Additionally, the scaffold generator will also add corresponding routes for the User resource in the config/routes.rb file, allowing you to access the generated CRUD actions through URLs.

By using scaffolding, you can quickly generate a basic CRUD interface for a model in Rails, saving you time and effort in setting up the initial structure of your application. However, keep in mind that scaffolding is often considered a starting point and may require further customization and refinement to match your specific application’s needs.

03#step — Open app/mailers/application_mailer.rb file and customize it for your Gmail account:

app/mailers/application_mailer.rb👇️:

class ApplicationMailer < ActionMailer::Base
default from: "<your_usename@gmail.com>"
layout "mailer"
end

🎶️ What is this life for 🎼️ , oops, what is this file for?

In Rails 7, the application_mailer.rb file located in the app/mailers the directory is the base mailer class from which other mailers in your application inherit. It provides common functionality and configuration options for sending emails.

The ApplicationMailer class is typically defined as follows:

class ApplicationMailer < ActionMailer::Base
default from: 'from@example.com'
layout 'mailer'
end

Let's understand what each part of this file does:

  1. class ApplicationMailer < ActionMailer::Base: This line declares the ApplicationMailer class and specifies that it inherits from ActionMailer::Base, which is the base class for all mailers in Rails.
  2. default from: 'from@example.com': This line sets the default email sender address for all emails sent from your application. You can change 'from@example.com' to your desired default sender address. This means that if you don't explicitly specify a sender in a mailer method, this default address will be used. Replace from@example.com with your Gmail address.
  3. layout 'mailer': This line specifies the layout file to be used for rendering the email views. The 'mailer' layout is a common convention for email views and typically resides in the app/views/layouts directory. This layout provides a common structure and styling for your email templates.

By defining the ApplicationMailer as the base class for all mailers in your application, you can inherit the default behavior and configuration options provided by ActionMailer::Base. You can also add custom methods, common helper methods, or other shared functionality in the ApplicationMailer class, which will be available to all other mailers.

It's worth noting that you can configure additional settings and options for email delivery in the config/environments/*.rb files, such as specifying the mail delivery method (SMTP, Sendmail, etc.), configuring SMTP settings, or setting up email templates. The Rails documentation provides more details on configuring email settings in Rails 7.

04#step — Generate the mailer:

rails g mailer UserMailer

The code rails g mailer UserMailer is a command in Rails to generate a mailer called UserMailer.

When you execute this command in the terminal, Rails will create a new mailer file (user_mailer.rb) in the app/mailers directory, along with a corresponding view directory (app/views/user_mailer).

The generated mailer file (user_mailer.rb) is a subclass of ActionMailer::Base, which is the base class for mailers in Rails. It allows you to define methods for sending different types of emails.

05#step — Define a method (inside ActionMailer subclass) to send an email:

For our example we want to send a welcome email to a new user, we can define a method like this in the UserMailer class, inside app/views/user_mailer👇️ create a file user_mailer.rb and type:

class UserMailer < ApplicationMailer
def welcome_email(user)
@user = user
mail(to: @user.email, subject: 'Welcome to My Awesome Site')
end
end

In this example, the welcome_email method takes a user object as a parameter. It sets an instance variable@user, which can be accessed in the corresponding view file.

06#step — Define routes inside config/routes.rb 👇️:

Rails.application.routes.draw do
resources :users
root "pages#index"
get 'signup', to: 'users#new'
end

In Rails 7, the code we provided is used to define the application routes using the Rails router.

Let’s break down the code:

  1. Rails.application.routes.draw do: This block is the entry point for defining the application routes.
  2. resources :users: This line generates RESTful routes for the users resource. It creates multiple routes for CRUD operations on users, such as index, show, new, create, edit, update, and destroy. For example, the GET /users route maps to the index action of the UsersController, which lists all users. The GET /users/:id route maps to the show action, which shows a specific user. The POST /users route maps to the create action, which creates a new user, and so on.
  3. root "pages#index": This line sets the root path route ("/") of the application to the index action of the PagesController. The index action is typically used to display the home page or the main entry point of the application.
  4. get 'signup', to: 'users#new': This line creates a custom route for the URL path /signup. It maps the request to the new action of the UsersController. This is often used to display a signup form or page for new users to register. In our case, a sign-up confirmation email is sent to the recipients for the verification that they have successfully subscribed for our web page service.

By using the Rails router and defining routes in this way, you can map HTTP requests to specific controller actions and build a RESTful interface for your application. The Rails routing guide (https://guides.rubyonrails.org/routing.html) provides more details and options for defining routes in Rails.

07#step — Create User Controller:

app/controllers/pages_controller.rb👇️:

class PagesController < ApplicationController 
end

08#step — Create Welcome page:

Create new file (index.html.erb) inside app/views/pages directory (remember in step #5 that our route is root pages#index); type:

app/views/pages/index.html.erb 👇️:

<h1>Welcome to Send Email w/ Rails 7 App!</h1>
<h3>Instructions</h3>
<h4>. Click Sign Up and Fill out the form;</h4>
<h4>. Enter a VALID EMAIL ADDRESS, please;</h4>
<h4>. An email will be sent to this address containing a confirmation link.</h4>
<%= button_to("Sign Up", '/signup', method: :get) %>
<h6>Thank you for use this app!</h6>

This HTML code presents a welcome page with instructions for signing up and using a Rails 7 application that involves sending emails. Once the user is routed to the root (TO DO: logged in), they get access to this page. It guides the user to click the Sign Up button, fill out the form with a valid email address, and explains that a confirmation email will be sent to that address.

09#step — Creating the views:

The corresponding view file (welcome_email.html.erb or welcome_email.text.erb) should be created in the app/views/user_mailer directory. This view file defines the content and layout of the email that will be sent:

app/views/user_mailer/welcome_email.html.erb👇️:

<h1>Welcome <%= @user.name %> to Send Email in Rails 7 App! </h1>
<p>
You have successfully signed up to this app!
Your username is: <%= @user.name %>.<br>
</p>
<p>Thanks for joining and have a great day!</p>

app/views/user_mailer/welcome_email.txt.erb👇️:

Welcome <%= @user.name %> to Send Email in Rails 7 App!
=======================================================
You have successfully signed up to this app!
Your username is: <%= @user.name %>.
Thanks for joining and have a great day!

After generating the mailer and defining the necessary methods and views, you can use the UserMailer to send emails from your Rails application. For example, to send the welcome email to a user, you can call:


UserMailer.welcome_email(user).deliver_now

Replace user with the actual user object, you want to send the email to.

Remember to customize the email content, add attachments, configure email delivery settings, and handle any other requirements specific to your application. The Rails documentation provides more details on advanced email features and customization options.

10#step —Configuration for Gmail:

config/environments/development.rb 👇️:

# config.action_mailer.delivery_method = :sendmail
# Defaults to:
# config.action_mailer.sendmail_settings = {
# location: '/usr/sbin/sendmail',
# arguments: '-i'
# }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: '<your_usename@gmail.com>'}

Important Note: Comment out these two lines in your file (so it will not be duplicated)👇️:

# config.action_mailer.raise_delivery_errors = false
# config.action_mailer.delivery_method = :sendmail

Copy right below this chunk of code:

  config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'JAYTHREE',
user_name: '<your_usename@gmail.com>',
password: 'GOTO: https://myaccount.google.com/apppasswords',
authentication: 'plain',
enable_starttls_auto: true }

Using Rails credentials:

  config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: Rails.application.credentials.gmail.domain,
user_name: Rails.application.credentials.gmail.user_name,
password: Rails.application.credentials.gmail.password,
authentication: 'plain',
enable_starttls_auto: true }

To setup credentials file:

Run:

EDITOR="code --wait" rails credentials:edit

You will need An app password.

An app password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App passwords can only be used with accounts that have 2-step Verification turned on.

Please GO TO: https://myaccount.google.com/apppasswords and set yours.

My domain is JAYTHREE, the name of my key and laptop.

11#step — Calling the email;

Our solution is to inject this code in users#create the method:

app/controllers/users_controller.rb👇️:

UserMailer.welcome_email(@user).deliver_now
# POST /users or /users.json
def create
@user = User.new(user_params)

respond_to do |format|
if @user.save
UserMailer.welcome_email(@user).deliver_now
format.html { redirect_to user_url(@user), notice: "User was successfully created. An email has been sent" }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end

The code we provided is User’s create action in a Rails 7 controller. This action is typically used to handle the creation of a new user record and perform related tasks, such as sending a welcome email. Let's break it down:

def create
@user = User.new(user_params)

This code initializes a new User object with the data submitted from a form. The user_params method is expected to return a sanitized and permitted set of parameters, typically obtained using strong parameters.

respond_to do |format|
if @user.save
UserMailer.welcome_email(@user).deliver_now
format.html { redirect_to user_url(@user), notice: "User was successfully created. An email has been sent." }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end

This block of code is a common pattern used to handle the response to the create action. It responds differently depending on the format of the request (html or json) and the success or failure of saving the @user object.

If @user.save is successful, meaning the user record is saved to the database, the code proceeds with the following actions:

  • It calls the welcome_email method of the UserMailer to send a welcome email to the newly created user;
  • It redirects the user to the show action of the users controller, displaying the newly created user's details;
  • It sets a flash notice to inform the user that the user was successfully created and that we sent you an email;
  • It returns a JSON response with the status :created and the location of the created user;

If @user.save fails, meaning there were validation errors or other issues with saving the user, the code proceeds with the following actions:

  • It renders the new view, allowing the user to correct any errors and resubmit the form;
  • It sets the response status to :unprocessable_entity, indicating that there were validation errors or issues with the request;
  • It returns a JSON response with the errors of the user object.

12#step — Run Rails Server

rails s
fig-2. Welcome page rendered! Click & Enjoy 😉️
fig-3. Email has been sent…
fig-4. Email received! 📧️ 👈️
fig-5. Details about the email sent. Emails are a fast, inexpensive, and accessible way to communicate for business or personal use.

That’s all folks

👉️GitHub

Here are some ideas on how you can leverage email technology in your application:

  1. User Registration and Onboarding: Send a welcome email to new users when they sign up, providing them with important information about their account, how to get started, and any necessary activation or verification steps.
  2. Notifications and Reminders: Send notifications to users for various events or updates within your application. For example, notify users about new messages, friend requests, order confirmations, upcoming appointments, or changes to their accounts.
  3. Password Reset: Allow users to reset their passwords by sending them a password reset email containing a unique link. This helps users regain access to their accounts securely.
  4. Transactional Emails: Send transactional emails for specific events triggered by user actions. Examples include order confirmations, shipping notifications, payment receipts, and booking confirmations.
  5. Newsletter and Marketing Campaigns: Maintain a mailing list and send newsletters or marketing campaigns to keep users engaged, and inform them about new features, promotions, or updates related to your application.
  6. Account Notifications: Inform users about important updates or changes related to their account, such as account suspensions, plan upgrades, subscription renewals, or payment failures.
  7. Activity Digests: Send regular or periodic summaries of user activity within your application. This can include updates on new content, recent interactions, or personalized recommendations based on their usage patterns.
  8. Feedback and Surveys: Request user feedback or conduct surveys via email to gather valuable insights, opinions, or ratings on your application or specific features.
  9. Social Notifications: Send email notifications about user activity within a social networking or community-driven application. For example, notify users when they receive friend requests, comments, likes, or when their posts are shared.
  10. Admin and Support Communication: Enable users to contact support or send messages to administrators through email. Respond to inquiries, provide assistance, and ensure smooth communication channels.

These are just a few ideas to inspire you. The possibilities for using email technology are vast and can be customized to your application’s specific needs and objectives. Remember to follow best practices for email deliverability, personalization, and respecting user preferences for opting in or out of receiving emails.

I Hope This Helps in Some Way …

Bye👋️ for now!

References & Credits

Rails Mailer Tutorial —By Eric Schwartz — Full stack web developer with experience in JavaScript, React/Redux, and Ruby on Rails. Musician turned coder.

Email —A Really Ruby Mail Library — By Mikel Lindsaar

The Complete Guide to Ruby on Rails Encrypted Credentials by Andy Leverenz

Possible errors:

Net::SMTPAuthenticationError in UsersController#create

535–5.7.8 Username and Password not accepted. Learn more at

Email encryption in transit

Related Posts:

00# Episode — RailsSeries — Installing Ruby on Rails Using ASDF — Why ASDF is Better Than RBENV for Rails Bootstrap App?

01# Episode — RailsSeries — How To Send Email In Rails 7? — User Registration and Onboarding (this one)

02# Episode — RailsSeries — 14 Ruby Extensions 4 Vs Code — Based On This Deanin’s video.

03# Episode — RailsSeries — A Rails Blog In VS Code — Quick Start — How To Create A Blog in VS Code — Part I

04# Episode — RailsSeries — A Rails Blog In VS Code — Styling — How To Create A Blog in VS Code — Part II

05# Episode — RailsSeries — A Rails Blog In VS Code — Create Posts — How To Create A Blog in VS Code — Part III

06# Episode — RailsSeries — A Rails Blog In VS Code — Posts Tips&Tricks — How To Create A Blog in VS Code — Part IV

07# Episode — RailsSeries — A Rails Blog In VS Code — Devise — How To Create A Blog in VS Code — Part V

08# Episode — RailsSeries — A Rails Blog In VS Code — Add Comments to Post — How To Create A Blog in VS Code — Part VI

09# Episode — RailsSeries — Rails Blog In VS Code — Using Stimulus — How To Create A Blog in VS CodePart VII

10# Episode — RailsSeries — Rails Blog In VS Code — Noticed V1 — Notifications for your Ruby on Rails app — Part VIII

11# Episode — RailsSeries — Rails Blog In VS Code — Noticed V2 — Notifications for your Ruby on Rails app — Part IX

--

--

J3
Jungletronics

😎 Gilberto Oliveira Jr | 🖥️ Computer Engineer | 🐍 Python | 🧩 C | 💎 Rails | 🤖 AI & IoT | ✍️