Wednesday, February 25, 2009

Creating a Ruby on Rails Mailer

So this is a pretty easy task to accomplish.

From the command line switch to the directory where your app is located. Enter the following command

  script/generate mailer notifier
This will create a model called notifer.rb, a folder under the views folder called notifier, it will create other files as well but these are the main two to be concerned with.

In views/notifier is where we will be creating erb templates to be the actual email that gets sent out to the end user.

In the notifier model, you'll want to setup functions that you will call from your controller in order to send the email. Here are a couple of examples I have created for my user email functions

class UserNotification < ActionMailer::Base
  def password_reset_code(user)
    @recipients   = "#{}"
    @from         = " "
    @subject      = "Your requested a password reset."
    @sent_on      =
    @body         = { :user =< user }
  def reset_notification(user)
    @recipients   = "#{}"
    @from         = " "
    @subject      = "Your password has been reset."
    @sent_on      =
    @body         = { :user =< user }
As you can probably tell this will setup two emails one for sending a reset code the other to verify the password has been reset.

In your controller, you simply call the Model in my example its called UserNotification.

The @user is an instance variable I created a couple of lines up that is a simple query to find the current user that is logged in. Notice you always prepend the Mailer function name with "deliver_".

Back up in our UserNotification functions you see for the @body variable we assign a simple hash. The hash will contain a link to all the model data passed into it. And will make that data available in the view. To reference the data simply use the instance variable, in our case @user to gain access to the model data.

Here is an example view


Here is your password reset code:


Please copy and paste the url below into your browser in order to reset your password:{@user.password_reset_code}

No comments:

Post a Comment

Raspberry Pi Zero W - Wireless Configuation

create the file under "boot" folder wpa_supplicant.conf country=GB ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev u...