How to Send a mail using Gmail account with Rails3, ActionMailer and SMTP


Hi friends,

Action Mailer:

Action Mailer is a framework for building e-mail services. You can use Action Mailer to receive and process incoming email and send simple plain text or complex multipart emails based on flexible templates.

Lets see how to setup the actionmailer with Gmail SMTP.

First we have to create a rails application using

   $ rails new action_mailer

Next we’ll generate a scaffold for a User model with name and email attributes to act as a simple user-registration page.

$ rails genetate scaffold user name:string email:string

Now we have to migrate with DB.

$ rake db:migrate

The generated scaffolding code includes a page for creating users. We want to create a new user and then send them a confirmation email when the form on this page is submitted.

Now, just run the rails server command,

$ rails s

Then, open the “http://localhost:3000

Adding New User

The first thing we’ll do is create a new initializer file called setup_mail.rb and put some configuration options in it. ActionMailer will use sendmail if it’s set up on your machine but we can instead specify SMTP settings in the initializer.

  $ cd /config/initializers/

  $ gedit setup_mail.rb

ActionMailer::Base.smtp_settings = {  
      :address              => "smtp.gmail.com",  
      :port                 => 587,  
      :domain               => "gmail.com",  
     :user_name            => "thasuresh", #Your user name
      :password             => "actionmailer", # Your password
      :authentication       => "plain",  
      :enable_starttls_auto => true  
   }

You’ll probably want to use a different approach in a production application but this is a good enough approach while our application is in development. Obviously you’ll want to change the domain, user_name and password options to suit your own Gmail account.

Now that we’ve completed the configuration we can generate a new mailer with the following code:

  $ rails generate mailer user_mailer

$ cd /app/mailer

  $ gedit user_mailer.rb


class UserMailer < ActionMailer::Base
default :from => "thasuresh@gmail.com"

def registration_confirmation(user)
mail(:to => user.email, :subject => "Registered")
end
end

Now we have to create a file called registration_confirmation.text.erb under app/views/user_mailer.

  $ gedit app/views/user_mailer/registration_confirmation.text.erb

Thank you for registering!

/app/controllers/users_controller.rb  (Note the 6th line)


def create
@user = User.new(params[:user])

respond_to do |format|
if @user.save
UserMailer.registration_confirmation(@user).deliver  #include this line in your users_controller.rb file
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end

mail sent by "ActionMailer"

If you want add user name at the mail, add the following line into registration_confirmation.text.erb

/app/views/user_mailer/registration_confirmation.text.erb.

<%= @user.name %>,

Thank you for registering!

Added User name

Now if you want add any attachments in the mail add this line into /app/mailer/user_mailer.rb


def registration_confirmation(user)
@user = user
attachments["rails.png"] = File.read("#{Rails.root}/public/images/rails.png")
mail(:to => "#{user.name} <#{user.email}>", :subject => "Registered")
end

Here my need is send a numeric password, when a user subscribe with his mail id. The password will send by actionmailer. So i added the a single ruby command into


Hi <%= @user.name %>,

This is the one time password, You can login into our site using the password given below

Password: <%=rand(999999)%>

Thank You For Registering!

Final output 🙂

That’s all !!!

Here sample “actionmailer” application and which deployed in heroku http://actionmailer.heroku.com

GitHub Account link: https://github.com/thasuresh/action_mailer

Advertisements

7 thoughts on “How to Send a mail using Gmail account with Rails3, ActionMailer and SMTP

  1. Ey guy i like this blog and the information is usefull but i have one comment for you
    i dont think this picture is healthy for this blog
    you understand me, is not
    sincerely you can change the picture
    just kidding
    this blog is usefull

    • Hi Victor,
      Greetings and thanks for your comment, Some of my friends also said to me, change my blog pic., and some of my friends said don’t change it. I thought of changing the pic., But I didn’t have time to search some good picture.Anyway today i changed the picture. 🙂

  2. hi, great post, especially for someone like me who is totally new to ROR. with regards to the addition of , in the reg confirmation text file which i have done, i get the following error
    undefined method `name’ for nil:NilClass

    Extracted source (around line #2):

    1:
    2: Hi ,
    3:
    4: Thanks for registering with

    do you have any ideas why this happens?

  3. sorry that didnt seem to come across clear

    the addition if gives error message “undefined method `name’ for nil:NilClass” when registering new user

  4. Fixing that “undefined method ‘name’ for nil:NilClass”
    use an @user in registration_confirmation method:
    def registration_confirmation(user)
    @user = user
    mail(:to => @user.email, :subject => “Registered”)
    end
    Now Try to access @user.name in the .text.erb file and it will work nicely. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s