Using GMail to Send Email on Ruby on Rails 2.3
I know that Rails is now on 3.2 but since some of my apps were developed under the previous version of rails, I have no choice but to work with it.

Objective


  • To use GMail or Google's server to enable email sending on your site.
  • This method should also be applicable even on your development environment aka localhost.
  • The method should work for version 2.3.8 of rails.


Specification

  • Rails 2.3 (currently I'm on 2.3.8)
  • Ruby 1.8.6
  • Gem 1.3.7

Steps

  1. First is install ambethia-smtp-tls gem for the TLS issue. If you will not install this, you might get this error:

    Net::SMTPAuthenticationError (530 5.7.0 Must issue a STARTTLS command first.

    To install:
    gem install ambethia-smtp-tls -v '1.1.2' --source http://gems.github.com/
    

  2. Next is open environment.rb and add this at the end of the file. Note that I said "end of the file" meaning it should be outside the Rails::Initializer.run block

    require 'smtp-tls'
    
    ActionMailer::Base.delivery_method = :smtp
    ActionMailer::Base.smtp_settings = {
       :address => "smtp.gmail.com",
       :port => 587,
       :domain => "gmail.com",
       :authentication => :plain,
       :user_name => "gmailusername",   # don't put "@gmail.com" here, replace this with your email's username
       :password => "gmailpawwsord", # replace with your gmail's password
       :enable_starttls_auto => true }
    

  3. Now create a mailer:

    ruby script/generate mailer Notifier
    

  4. Open app/models/notifier.rb and copy this code

    def sendmail(email_from, email_to, sender_name, subject, message)
     from   email_from
     recipients  email_to
     subject  "Contact Form: " + subject
     body(:sender => email_from, :message => message, :subject => subject, :sender_name => sender_name)
    end
    

  5. Inside the folder app/views/, Create a file named sendmail.html.erb and copy the following:
    A message coming from <%= @sender_name + " (#{@sender})" %>
    <br />
    <br />
    <b>SUBJECT:</b> <%= @subject %><br/>
    <br />
    <b>MESSAGE:</b>
    <fieldset>
     <%= @message %>
    </fieldset>
    

    NOTE: You can alsoo customize it depending on the message you will sent over the email. You can use HTML tags for customizing the look of it.

  6. Configurations and layouts should now be fine. You can now call this function to any part of your controllers in order to use it. Just follow this syntax:

    Notifier.deliver_sendmail([EMAIL-FROM], [EMAIL-TO], [SENDER-NAME], [SUBJECT], [MESSAGE] )
    
    Take note that I used the word deliver_ before the model attribute.


And that should do the trick for this version of rails. You may also customize the function and layout of these code in order to get a more personal touch on it. :)


No comments :

Post a Comment