How To Send Email with Ruby and Gmail

Posted: 07/08/2009

I previously posted about sending email from Rails through your Gmail account. This is the first of two posts demonstrating sending and receiving emails from any old Ruby script. For sending emails, I wanted an interface like this:

  gmail = GmailSender.new(:login => 'yourgmail@example.com', 
                          :password => 'yourpass')
                       
  gmail.deliver(:to => 'friend@example.com', 
                :subject => 'Ricky A',
                :body => "ShirtsTasteGood has two rick astley shirts")

This is my implementation: [shrink code]

require 'net/smtp'
require 'rubygems'
require 'tlsmail'
  
Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
  
class GmailSender
  SMTP_ADDR = 'smtp.gmail.com'
  
  def initialize(opts = {})
    unless opts[:login] && opts[:password]
      raise ArgumentError.new("provide login and password") 
    end
    @login = opts[:login]
    @password = opts[:password]
    @domain = @login[/@(.+)$/,1]
  end
  
  def deliver(opts = {})
    tostr = opts[:to].is_a?(Array) ? opts[:to].join(', ') : opts[:to]
    msg = ["FROM: #{@login}",
           "TO: #{tostr}",
           "SUBJECT: #{opts[:subject]}"]
    msgstr = msg.join("\n") << "\n\n#{opts[:body]}"
    smtp_args = [SMTP_ADDR, 25, @domain, @login, @password, :login]
    Net::SMTP.start(*smtp_args) do |smtp|
      status = smtp.send_message msgstr, @login, opts[:to]
      puts status
    end
  end
end

I made this single file into a local gem, so now I’m ready to write command line email hacks to my heart’s content. Now if you are thinking, “why don’t you just use ActionMailer and tlsmail like you did in the Rails example?” Well, this is the best explanation I’ve got. Next up, receiving emails from GMail!

About Me

I'm a skier, web developer, entrepreneur, freelancer, and all around stand-up guy living in Manhattan. This is me, repping one of my favorite shirts...

Follow me on twitter or send me an email.

All Posts