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:
-- 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
# 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:
# 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!
# 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
Password:
postfix/postfix-script: starting the Postfix mail system
Everything should be working! Was this helpful? Link to me and leave a comment!