Shiva Bhusal
Shiva's Blog


Shiva's Blog


Easiest way to send EMail via Rails : Action mailer

Shiva Bhusal's photo
Shiva Bhusal
·Sep 29, 2014·

3 min read

Play this article

Action Mailer

Action Mailer allows you to send emails from your application using mailer classes and views.

Mailers are similar to controllers 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.


It’s very easy to send Email via rails 3 and above. You just need to write few lines of codes and you are done. There are two ways you want to send email

  1. You can just send email via any Email address you wish, eg:
  2. Next is, you can send email via email servers of any services you are registered with, such as Google Mail, Outlook, sendgrid etc

The First way: Sending Email from anonymous Email Address

Create a file names setup_mail.rb in config/initializers/ directory and write the following code


ActionMailer::Base.smtp_settings = {
 :address => "",
 :port => 25
 } is the smtp address of my ISP, see this for your ISP in your ISP's website

#25 is default port number for SMTP, see if it is different for your's ISP

Then generate a mailer ( Mailer is just like controller). Write following code to generate mailer

rails generate mailer mailer_name

eg: rails g mailer user_mailer

This will create a file names user_mailer.rb in app/mailers directory and user_mailer directory in app/views directory

replace the codes in the file with following


class UserMailer < ActionMailer::Base
    mail(:to => '', :subject => "Newly Registered", :from => "")

#'' can be replace with if you have sentUserobject via method call

Like controllers, mailers also have views associated with it in views directory. No file is deafulty created in views directory, you just need to create one. Create a file named registration_confirmation.html.erb in user_mailer directory and write text you want your user to see in email. Like

<h1>Thank you dear for registering</h1>  
<p>The new one</p>

You can also embed ruby code as in other views. You can also render these views to see Email Preview.

Now you need to trigger the rails to send the Email. You can do this by invoking the action you created in mailer. In this  case




def create  
    @user =[:user])


To send Email via Google, or Microsoft Mail servers, you need to change settings in setup_mail.rb file

ActionMailer::Base.delivery_method = :smtp

ActionMailer::Base.smtp_settings = {
  :address => "",
  :port => "587",
  :domain => "",
  :user_name => "",
  :password => "yyy",
  :authentication => "plain",
  :enable_starttls_auto => true

For Outlook just change the attributes according to the vendor

Share this