Action Mailer is the Rails component that enables applications to send and receive emails. The other email related component in the Rails framework is Action Mailbox, which deals with receiving emails.
Action Mailer
Action Mailer uses mailers classes and views to create and configure the email to be sent. Mailer class inherits from ActionMailer::Base. It is similar to controller classes, as it also has:
Instance variables
It can use layouts and partials
It has access to a params hash
It also defines actions and associated views in app/views
Let’s start creating a new project using the following command –
rails new mailtest
This will create the required framework to proceed. Now, we will start with configuring the ActionMailer.
Action Mailer – Configuration
Follow the steps given below to complete your configuration before proceeding with the actual work –
Go to the config\environments folder of your project and open development.rb file and add the following line inside the Rails.application.configure do block.
config.action_mailer.delivery_method =:smtp
It tells ActionMailer that you want to use the SMTP server. You can also set it to be :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux.
This configuration file has many configuration settings. Keep them unchanged, configure smtp setting as follows to use Gmail for sending email:
Rails.application.configure do# Other existing settings...# Configure mailer settings for Gmail SMTP
config.action_mailer.delivery_method =:smtp
config.action_mailer.smtp_settings ={
config.action_mailer.perform_deliveries =true# Ensure emails are actually sent
config.action_mailer.raise_delivery_errors =true# Show errors for debuggingend
Replace each hash value with proper settings for your Simple Mail Transfer Protocol (SMTP) server. You can take this information from your Internet Service Provider if you already don’t know. You don’t need to change port number 25 and authentication type if you are using a standard SMTP server.
Note that Gmail has strict security policies. To send emails from your app, you can enable Less Secure Apps access in your Google account. However this feature not available for accounts with 2 Factor Authentication. In such case, the preferred option is to use an App Password instead of your real password. You can generate it in your Google Account Security settings.
You may also change the default email message format. If you prefer to send email in HTML instead of plain text format, add the following line to the development.rb as well −
ActionMailer::Base.default_content_type could be set to “text/plain”, “text/html”, and “text/enriched”. The default value is “text/plain”.
The next step will be to generate a mailer.
Generate a Mailer
Use the following command to generate a mailer as follows –
rails generate mailer UserMailer
This will create a file user_mailer.rb in the app\mailer directory. Check the content of this file as follows −
classEmailer<ActionMailer::Baseend
Let’s add the welcome_email method as follows −
classUserMailer<ApplicationMailer
default from:" GMAIL_USERNAME"defwelcome_email(user)@user= user
mail(to:@user.email, subject:"Welcome to My Awesome Site!")endend</pre>
default Hash − This is a hash of default values for any email you send from this mailer. In this case we are setting the :from header to a value for all messages in this class. This can be overridden on a per-email basis
mail − The actual email message, we are passing the :to and :subject headers in.
Create a file called welcome_email.html.erb in app/views/user_mailer/. This will be the template used for the email, formatted in HTML –
<h1>Welcome to example.com, <%= @user.name %></h1><p>
You have successfully signed up to example.com,your username is:
<%= @user.email %>.<br></p><p>
To login to the site, just follow this link:
<%= @url %>.
</p><p>Thanks for joining and have a great day!</p>
You can also create Plain text email view in app/views/user_mailer/welcome_email.text.erb:
Welcome to example.com,<%= @user.name %>
===============================================You have successfully signed up to example.com,Your username is:<%= @user.email %>.
To login to the site, just follow this link: <%=@url%>.Thanksfor joining and have a great day!
Calling the Mailer
First, let's create a simple User scaffold.
rails generate scaffold User name:string email:string
Then, run migrations:
rails db:migrate
This will create User model, UsersController class with new, create, edit, update, destroy, index, show actions and the corresponding views such as new.html.erb, edit.html.erb, etc.
Modify UsersController to Send Email on User Creation
Edit the Create action in app/controllers/users_controller.rb to send a welcome email after a user is created:
UserMailer.welcome_email(@user).deliver_now # Send email after user creation
redirect_to @user, notice:"User was successfully created. A welcome email has been sent."else
render :new, status::unprocessable_entityendendprivatedefuser_params
params.require(:user).permit(:name,:email)end</pre>
Ensure that the UsersController also has the show action as follows:
defshow@user=User.find(params[:id])end
The set_user method stores the current user in the @user instance variable.
That’s it. Now, to test your application start the server and visit http://127.0.0.1:3000/users/new. It displays the following screen to add a new user
This adds a new User object and calls the welcome_email method to generate the welcome email, using the Gmail address set in the configuration.
While the user can verify that he has received the email, the app redirects the browser to show the confirmation.
On the console, you get the following log:
UserMailer#welcome_email: processed outbound mail in 148.6msDelivered mail [email protected] (22000.3ms)Date:Thu,03Apr202512:22:33+0530From:*****@gmail.com
To:*****@gmail.com
Message-ID:<[email protected]>Subject:Welcome to MyAwesomeSite!Mime-Version:1.0Content-Type: multipart/alternative;
boundary="--==_mimepart_67ee3030ed242_73d4638841e";
charset=UTF-8Content-Transfer-Encoding:7bit
----==_mimepart_67ee3030ed242_73d4638841e
Content-Type: text/plain;
charset=UTF-8Content-Transfer-Encoding:7bit
For more information on how to send emails using Rails, please go through the official documentation on ActionMailer (https://guides.rubyonrails.org/action_mailer_basics.html)
Leave a Reply