Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Generic ActionMailers make Rails e-mails easy

By Peter Cooper / June 4, 2006

A few months ago I was getting fed up of having to create new ActionMailers from scratch on my Rails applications, so I decided to come up with a 'generic' way to cover all the bases. Instead of creating multiple mailers, you create a single mailer and append generic methods. The content goes to the regular RHTML files and you send through whatever you want from your controllers. See Simplifying ActionMailer development in Ruby on Rails. There's probably a lot that could be done to it now, but it works great for me.

An example ActionMailer class:

class Mailer < ActionMailer::Base

  helper ActionView::Helpers::UrlHelper

  def generic_mailer(options)

    @recipients = options[:recipients] || "me@privacy.net"
    @from = options[:from] || "me@privacy.net"

    @cc = options[:cc] || ""
    @bcc = options[:bcc] || ""

    @subject = options[:subject] || ""
    @body = options[:body] || {}

    @headers = options[:headers] || {}
    @charset = options[:charset] || "utf-8"

  end

  # Create placeholders for whichever e-mails you need to deal with.
  # Override mail elements where necessary

  def contact_us(options)
    self.generic_mailer(options)
  end
  ...
end

An example delivery call from a controller:

Mailer.deliver_contact_us(
   :recipients => "x@x.com",
   :body => {
               :name => params[:name],

               :phone => params[:phone],
               :email => params[:email],

               :message => params[:message]
             },
   :from => "y@y.com"
)

Other Posts to Enjoy

Twitter Mentions