DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simplifying ActionMailer Development In Ruby On Rails

  • submit to reddit
        Sick of writing almost the same thing over and over in your ActionMailer classes? Skip all that, and use something like this.

class Mailer < ActionMailer::Base

  helper ActionView::Helpers::UrlHelper

  def generic_mailer(options)
    @recipients = options[:recipients] || ""
    @from = options[:from] || ""
    @cc = options[:cc] || ""
    @bcc = options[:bcc] || ""
    @subject = options[:subject] || ""
    @body = options[:body] || {}
    @headers = options[:headers] || {}
    @charset = options[:charset] || "utf-8"
  # Create placeholders for whichever e-mails you need to deal with.
  # Override mail elements where necessary
  def contact_us(options)



<em>(If you have a configuration loaded into a constant, you could just replace the defaults above and use your app's defaults to make it all cleaner, of course)</em>

And then from your controller you can do stuff like this:

   :recipients => "",
   :body => { 
               :name => params[:name],
               :phone => params[:phone],
               :email => params[:email],
               :message => params[:message]
   :from => ""


Snippets Manager replied on Mon, 2012/05/07 - 1:19pm

I just took a break from working on an app to check my rss feeds: Next on the todo list was a 'contact us' form. Literally, I was going to write this same thing 10 minutes from now. You (and this site) rock.