ActionMailer in standalone apps

Today someone in #ruby-lang asked if you could use Rails' ActionMailer also in standalone ruby applications. That user left after a short time and the question stayed unanswered, although it is my opinion quite interesting :) So I started digging a little bit through the documentation and came up with a quite basic solution which actually holds no real suprises.

require 'rubygems'
require 'pp'
require_gem 'actionmailer'
ActionMailer::Base.template_root = 'templates'
ActionMailer::Base.delivery_method = :test
class TestMailer < ActionMailer::Base
  def test
    @recipients = ''
    @subject = 'Hello World'
    @from = ''
if $0 == __FILE__
  ActionMailer::Base.deliveries.each do |mail| 
    puts "#{'='*60}"
    puts "Subject: #{mail.subject}"
    puts "From: #{mail.from}"
    puts "To: #{}"
    puts "#{'-'*60}"
    puts "#{mail.body}"

As in Rails you simply create an ActionMailer subclass and do the deliver_action thing with it. The only thing that is slightly different here, is that you have to specify a template_root directory. The rest of the configuration should be the same as for its use in a Rails webapp (for details please read the manual) In this case I use the ‘templates’ folder in the same directory as the script (actually in the pwd but anyway ;)).

So for this example you would have to have following folder structure


Running this script should give you the expected mail :)

Note: I haven’t tested it with anything but the :test delivery_method, so perhaps there are some hidden problems :)