Rails send email tutorial

February 25, 2008

 
No Gravatar

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Postoffice < ActionMailer::Base  
# located in models/postoffice.rb
# make note of the headers, content type, and time sent
# these help prevent 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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_ prefix, 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!

  • chris
    Hey there,
    In your postoffice.rb, line #9 should be:
    @headers = {"Reply-to" => "#{email}"}
  • @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.
  • Matthew
    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.
  • nice write up.
  • Jonathan
    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!
  • Tobi
    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" )??
  • Shiraz
    You have not listed any settings for actionmailer like smtp host name/user/pwd etc.?
  • Hi
    Hi,

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

    Thanks
  • hihi
    Where does params[:contact][:email] come from? I don't see it passed anywhere.
  • Juanqui
    How do I configure my SMTP settings, etc... ?
  • Axel
    They are passed here on delivery:

    Postoffice.deliver_welcome(@user.name, @user.email)
  • Niklas
    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 :)).
  • Jose
    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
  • 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?
  • (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?
  • Eduardo M
    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
    }
  • Thanks buddy! Will get around to this eventually and link to you if all is successful!
  • Johannes
    @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)!
  • Nice! Thanks!
  • gemini
    is this example running on windows?
  • yes that was very helpful thankyou
  • kuttikrishnan
    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
  • Nice and quick - many thanks!
blog comments powered by Disqus