Sending mail with Ruby and ActionMailer

This is a simple, but useful little script I ended up writing to test some things. I found it easier to use this than to constantly use the mail command. It basically wraps action mailer in a small ruby script so you can call it from the command line.

./spoofmail.rb --subject='Hey You!' --body='whatsup guy?'

or using STDIN

./spoofmail.rb --subject='Hey You!' < body_of_message

cat|./spoofmail.rb --subject='Hey You!'
whatsup guy?

It might come in handy one day when you need to mess with a co-worker or test a mail receiver… or something else?


require 'rubygems'
require 'action_mailer'
require 'optparse'
require 'fcntl'
require 'pp'

ActionMailer::Base.delivery_method = :sendmail

  :to => [''],
  :subject => 'Hello World!',
  :from => '',
  :body => 'Hello World!'

class Mailman < ActionMailer::Base
  def test(options)
    recipients  options[:to]
    subject     options[:subject]
    from        options[:from]
    body        options[:body]

if __FILE__ == $0 do |o|
    o.banner = "Usage: #{$0} [options]"
    o.on('-t', '--to=user,user,user', Array, 'Comma separated email addresses.'){ |t| OPTIONS[:to] = t }
    o.on('-f', '--from=FROM', 'From email address.') { |f| OPTIONS[:from] = f }
    o.on('-s', '--subject=SUBJECT', 'Subject line.'){ |s| OPTIONS[:subject] = s }
    o.on('-b', '--body=BODY', "Email body. Also accepts STDIN: \"cat|#{$0}\""){ |b| OPTIONS[:body] = b }
  OPTIONS[:body] = if STDIN.fcntl(Fcntl::F_GETFL, 0) == 0

  puts "\n\nOptions:\n"
  puts "\nSending E-Mail:\n"
  puts "Sent!" if Mailman.deliver_test(OPTIONS)

View Gist