Rails send email tutorial

Want to send an email using Rails? I struggled with this for a while and I’m sure many of you do too. This post will cover the basic implementation of a mailer, it is tested to work in Rails 2.0.2.

Rails Mailer Overview

1) script/generate mailer postoffice
2) Create a method for your mailer (models/postoffice.rb)
3) Create your email template using welcome.text.html.erb and welcome.text.plain.erb (views/postoffice)
4) Deliver your message
5) If you’re testing locally, make sure postfix is running

Begin by opening your terminal:

add3-imac: jon$ rails mailer_example
  -- output truncated --

add3-imac: jon$ cd mailer_example/

add3-imac:mailer_example jon$ script/generate mailer postoffice
      exists  app/models/
      create  app/views/postoffice
      exists  test/unit/
      create  test/fixtures/postoffice
      create  app/models/postoffice.rb
      create  test/unit/postoffice_test.rb

Next, we are going to create a method for our mailer

class Postoffice < ActionMailer::Base  
# located in models/postoffice.rb
# make note of the headers, content type, and time sent
# these help codevent your email from being flagged as spam

  def welcome(name, email)
    @recipients   = "user@host.com"
    @from         = params[:contact][:email]
    headers         "Reply-to" => "#{email}"
    @subject      = "Welcome to Add Three"
    @sent_on      = Time.now
    @content_type = "text/html"
   
    body[:name]  = name
    body[:email] = email      
  end
 
end

Now that our method is created, let’s modify the email templates:

# located in views/postoffice
# we can access the variables we declared in models/postoffice.rb
# body[:name]  = name is accessed by @name
# body[:email] = email is accessedby @email

# welcome.text.html.erb
# note the HTML
<p>Welcome to AddThree <i><%= @name %></i>. </p>

<p>The address we have on file for you is <b><%= @email %></b>, please let us know if this is incorrect.</p>

# welcome.text.plain.erb
Welcome to AddThree <%= @name %>. The address we have on file for you is <%= @email %>, please let us know if this is incorrect.

Now that our mailer and templates arein place, let’s deliver the email!

class Registration < ApplicationController
# controllers/registration_controller.rb
# assume the Registration controller already existed
# assume @user.name and @user.email have been declared

  def send_welcome_email
    # triggered via:
    # http://localhost:3000/registration/send_welcome_email
   
    # note the deliver_ codefix, this is IMPORTANT
    Postoffice.deliver_welcome(@user.name, @user.email)
   
    # optional, but I like to keep people informed
    flash[:notice] = "You've successfuly registered. Please check your email for a confirmation!"
   
    # render the default action
    render :action => 'index'  
  end
 
 
end

If you’re testing locally, make sure postfix is running

add3-imac:mailer_example jon$ sudo postfix start
Password:
postfix/postfix-script: starting the Postfix mail system

Everything should be working! Was this helpful? Link to me and leave a comment!

Tags: , ,

45 comments

  1. Hey there,
    In your postoffice.rb, line #9 should be:
    @headers = {“Reply-to” => “#{email}”}

  2. Hey there,
    In your postoffice.rb, line #9 should be:
    @headers = {“Reply-to” => “#{email}”}

  3. @Chris: I don’t think so, you can either call the headers function or you can pass it directly to @headers variable

    Also, in my implementation, the email does get send but the redirection is not executed for some unknown reason.

  4. @Chris: I don't think so, you can either call the headers function or you can pass it directly to @headers variable

    Also, in my implementation, the email does get send but the redirection is not executed for some unknown reason.

  5. if I want to set a specific template/view to be used for the email, how would I do this? The template I want to use it dependent upon a web-user’s input.

  6. if I want to set a specific template/view to be used for the email, how would I do this? The template I want to use it dependent upon a web-user's input.

  7. All- I’ll address your comments shortly. I’ve been working non-stop to meet our April 2nd deadline for the free online dating site we’ve been working on!

  8. All- I'll address your comments shortly. I've been working non-stop to meet our April 2nd deadline for the free online dating site we've been working on!

  9. I’m confused, doesn’t suggest the rails api the usage of method calls( recipients “jon@addthree.com”) instead of class variables (@recipients = “jon@addthree.com” )??

  10. I'm confused, doesn't suggest the rails api the usage of method calls( recipients “jon@addthree.com”) instead of class variables (@recipients = “jon@addthree.com” )??

  11. You have not listed any settings for actionmailer like smtp host name/user/pwd etc.?

  12. You have not listed any settings for actionmailer like smtp host name/user/pwd etc.?

  13. Hi,

    Is it possible to use a smtp server like yahoo ? How can I configure this ?

    Thanks

  14. Hi,

    Is it possible to use a smtp server like yahoo ? How can I configure this ?

    Thanks

  15. Where does params[:contact][:email] come from? I don’t see it passed anywhere.

  16. Where does params[:contact][:email] come from? I don't see it passed anywhere.

  17. How do I configure my SMTP settings, etc… ?

  18. How do I configure my SMTP settings, etc… ?

  19. They are passed here on delivery:

    Postoffice.deliver_welcome(@user.name, @user.email)

  20. They are passed here on delivery:

    Postoffice.deliver_welcome(@user.name, @user.email)

  21. Nice tutorial!

    For all the ppl curious about the SMTP settings (like me), it may be helpful to have a look into the API documentation at

    http://www.gotapi.com/rubyrails

    Search for “ActionMailer::Base”, it’ll most likely tell you everything you wanted to know (worked for me :) ).

  22. Nice tutorial!

    For all the ppl curious about the SMTP settings (like me), it may be helpful to have a look into the API documentation at

    http://www.gotapi.com/rubyrails

    Search for “ActionMailer::Base”, it'll most likely tell you everything you wanted to know (worked for me :) ).

  23. Hi,
    I´m getting “initialize: name or service not known” when trying to send an email. Any clue? This is the entire trace:

    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/protocol.rb:206:in `new’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/protocol.rb:206:in `old_open’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/timeout.rb:56:in `timeout’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/timeout.rb:76:in `timeout’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/protocol.rb:206:in `old_open’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/smtp.rb:393:in `do_start’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/smtp.rb:378:in `start’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/smtp.rb:316:in `start’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/gems/1.8/gems/actionmailer-2.1.0/lib/action_mailer/base.rb:627:in `perform_delivery_smtp’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/gems/1.8/gems/actionmailer-2.1.0/lib/action_mailer/base.rb:508:in `deliver!’
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/gems/1.8/gems/actionmailer-2.1.0/lib/action_mailer/base.rb:383:in `method_missing’

    Thanks in advance

  24. Hi,
    I´m getting “initialize: name or service not known” when trying to send an email. Any clue? This is the entire trace:

    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/protocol.rb:206:in `new'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/protocol.rb:206:in `old_open'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/timeout.rb:56:in `timeout'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/timeout.rb:76:in `timeout'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/protocol.rb:206:in `old_open'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/smtp.rb:393:in `do_start'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/smtp.rb:378:in `start'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/1.8/net/smtp.rb:316:in `start'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/gems/1.8/gems/actionmailer-2.1.0/lib/action_mailer/base.rb:627:in `perform_delivery_smtp'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/gems/1.8/gems/actionmailer-2.1.0/lib/action_mailer/base.rb:508:in `deliver!'
    C:/Archivos de programa/NetBeans 6.1/ruby2/jruby-1.1.2/lib/ruby/gems/1.8/gems/actionmailer-2.1.0/lib/action_mailer/base.rb:383:in `method_missing'

    Thanks in advance

  25. Great, simple tutorial. You got me up and running with mail in no time!

    Question: Do you know if there is a method you can define that will run on all deliveries, much like the :before_create, :after_create, :after_save, etc. methods for models?

    For example, if I wanted to add an entry into a log each time an email was sent, how would I go about doing so in a DRY way, preferably without having to add a call to another method in each delivery method?

  26. Great, simple tutorial. You got me up and running with mail in no time!

    Question: Do you know if there is a method you can define that will run on all deliveries, much like the :before_create, :after_create, :after_save, etc. methods for models?

    For example, if I wanted to add an entry into a log each time an email was sent, how would I go about doing so in a DRY way, preferably without having to add a call to another method in each delivery method?

  27. (sorry, incorrect email in the previous post…)

    Great, simple tutorial. You got me up and running with mail in no time!

    Question: Do you know if there is a method you can define that will run on all deliveries, much like the :before_create, :after_create, :after_save, etc. methods for models?

    For example, if I wanted to add an entry into a log each time an email was sent, how would I go about doing so in a DRY way, preferably without having to add a call to another method in each delivery method?

  28. (sorry, incorrect email in the previous post…)

    Great, simple tutorial. You got me up and running with mail in no time!

    Question: Do you know if there is a method you can define that will run on all deliveries, much like the :before_create, :after_create, :after_save, etc. methods for models?

    For example, if I wanted to add an entry into a log each time an email was sent, how would I go about doing so in a DRY way, preferably without having to add a call to another method in each delivery method?

  29. SMTP setings in environment.rb:

    config.action_mailer.delivery_method = :smtp
    config.action_mailer.server_settings = {
    => “domain.of.smtp.host.net” ,
    :address
    :port => 25,
    => “domain.of.sender.net” ,
    :domain
    :authentication => :login,
    :user_name => “yourusername” ,
    => “secret”
    :password
    }

  30. SMTP setings in environment.rb:

    config.action_mailer.delivery_method = :smtp
    config.action_mailer.server_settings = {
    => “domain.of.smtp.host.net” ,
    :address
    :port => 25,
    => “domain.of.sender.net” ,
    :domain
    :authentication => :login,
    :user_name => “yourusername” ,
    => “secret”
    :password
    }

  31. Thanks buddy! Will get around to this eventually and link to you if all is successful!

  32. @Eduardo
    That's right, these lines are necessary.

    To avoid messing around with an error “uninitialized constant ActionMailer” for hours like I did, you should also make sure that you do NOT have the following line inside your environment.rb:

    config.frameworks -= [ :action_web_service, :action_mailer ]

    This line has to be commented out (or, at least, it may not contain :action_mailer)!

  33. is this example running on windows?

  34. yes that was very helpful thankyou

  35. Hi there can u tell me how to configure the smtp to send the mail and if there is any class for this purpose, where ca i get smtp in my local machine while using netbeans

  36. rertertertert

  37. Nice and quick – many thanks!

  38. hi, if no server mail. how send mail. Please help me

  39. Cool!!! Really this was too helpful for me..

  40. Cool!!! Really this was too helpful for me..

Leave a comment