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 --to=who@where.com --from=sjobs@apple.com --subject='Hey You!' --body='whatsup guy?'

or using STDIN

./spoofmail.rb --to=who@where.com --from=sjobs@apple.com --subject='Hey You!' < body_of_message

cat|./spoofmail.rb --to=who@where.com --from=sjobs@apple.com --subject='Hey You!'
whatsup guy?
^d

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

#!/usr/local/bin/ruby

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

ActionMailer::Base.delivery_method = :sendmail

OPTIONS = {
  :to => ['friend@domain.com'],
  :subject => 'Hello World!',
  :from => 'you@domain.com',
  :body => 'Hello World!'
}

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

if __FILE__ == $0
  OptionParser.new 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 }
  end.parse!(ARGV)
  
  OPTIONS[:body] = STDIN.read if STDIN.fcntl(Fcntl::F_GETFL, 0) == 0

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

View Gist