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 = 're@domain.com' @subject = 'Hello World' @from = 'sender@domain.com' end end if $0 == __FILE__ TestMailer.deliver_test ActionMailer::Base.deliveries.each do |mail| puts "#{'='*60}" puts "Subject: #{mail.subject}" puts "From: #{mail.from}" puts "To: #{mail.to}" puts "#{'-'*60}" puts "#{mail.body}" end end
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
./templates ./templates/test_mailer ./templates/test_mailer/test.rhtml ./test.rb
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 :)
Do you want to give me feedback about this article in private? Please send it to comments@zerokspot.com.
Alternatively, this website also supports Webmentions. If you write a post on a blog that supports this technique, I should get notified about your link π