Ruby on Rails Send Emails - Ruby on Rails

What is Action Mailer?

Action Mailer is the Rails component that enables applications to send and receive emails.

How to send an email using Rails

Start creating an emails project using the following command.

This will create the required framework to proceed.

How to configure the ActionMailer

Go to the config folder of your emails project and open environment.rb file and add the following line at the bottom of this file.

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.

Add the following lines of code at the bottom of your environment.rb as well.

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.

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 config/environment.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".

How to generate a Mailer

Use the following command to generate a mailer as follows −

This will create a file user_mailer.rb in the appmailer directory. Check the content of this file as follows −

Let's create one method as follows −

  • 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 −

Next we will create a text part for this application as follow −

How to call the Mailer

First, let's create a simple User scaffold

Action Mailer is nicely integrated with Active Job so you can send emails outside of the request-response cycle, so the user doesn't have to wait on it −

Now, test your application by using It displays the following screen and by using this screen, you will be able to send your message to anybody.

Send email

This will send your message and will display the text message "Message sent successfully" and output as follow −

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Ruby on Rails Topics