Thursday, October 15, 2009

send email through gmail via ruby 1.8.7 and later

this took me some searching and eventually talking to drbrain on freenode #ruby-lang. i then found that drbrain wrote the ruby gem smtp_tls which makes this work for 1.8.6 and possibly earlier. so that's kinda cool.

here's the minimal ruby example. put this in a file

require 'net/smtp'

host = 'smtp.gmail.com'
port = 587
relay_domain = 'example.com' #doesn't matter
send_account = 'gmail_account' # i.e. "example" from "example@google.com"
recv_account = 'receiver_account' #i.e. "acct" from "acct@example.com"
pw = "password"
auth_type = :login #:cram_md5 doesn't work

from ="#{send_account}@gmail.com"
to = "#{recv_account}@example.com"
subject = "subject line goodness"
body = "look, it's an email body!"

msg = <<END_OF_MESSAGE
From: #{from}
To: #{to}
Subject: #{subject}

#{body}
END_OF_MESSAGE

smtp = Net::SMTP.new host, port
smtp.enable_starttls
smtp.start(relay_domain, send_account, pw, auth_type) do |server|
server.send_message(msg, from, to)
end

No comments:

Post a Comment

Where am I?