Skip to content

Instantly share code, notes, and snippets.

@alexch
Created December 27, 2009 18:42
Show Gist options
  • Save alexch/264363 to your computer and use it in GitHub Desktop.
Save alexch/264363 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'tlsmail' # http://rubyforge.org/projects/tlsmail/
# see also http://www.stephenchu.com/2006/06/how-to-use-gmail-smtp-server-to-send.html
# Message - minimal emailer
# Author: Alex Chaffee <[email protected]>
#
# Usage:
#
# Message.new(:from => '[email protected]', :to => ['[email protected]', '[email protected]'], :subject => 'ohai', :body => "lol\ncats").send
#
# Message.fake - turn on test mode
#
# Message.sent - list of all emails sent in test mode
#
# Message.print_fakes - for development mode - prints emails to console if in fake mode
#
# TODO: read config from a file
#
class Message
@@fake = false
@@print_fakes = false
# activates "fake mode" and clears the sent queue
def self.fake
@@fake = true
@@sent = []
end
# if in fake mode, prints fake messages to console
def self.print_fakes
@@print_fakes = true
end
# if in fake mode, returns messages in order they were sent
def self.sent
@@sent
end
def self.site_url(path)
path = "/#{path}" unless path[0..0] == "/"
"http://www.cohuman.com#{path}"
end
attr_reader :from, :to, :subject, :body
def initialize(options)
@from = options[:from] || '[email protected]'
@to, @subject, @body = options[:to], options[:subject], options[:body]
end
def to
(@to.is_a?(String) ? [@to] : @to).compact
end
def to_s
"From: #{from}\nTo: #{to.join(', ')}\nSubject: #{subject}\n\n#{body}"
end
def send
return if to.empty?
if @@fake
if @@print_fakes
puts "[[ Pretending to send email:"
puts to_s
puts "]]"
end
@@sent << self
else
server = "smtp.gmail.com"
port = 587
helo = 'gmail.com'
user = '[email protected]'
secret = 'PASSWORD'
authtype = :plain
Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
smtp = Net::SMTP.new(server, port)
smtp.set_debug_output $stderr
smtp.start(helo, user, secret, authtype) do |smtp|
smtp.send_message to_s, from, to
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment