Code Like Zell

How to send email with Ruby and Gmail

Posted 08 July 2009.

For sending emails from my gmail account, I wanted to an interface like this:

  gmail = GmailSender.new(:login => 'yourgmail@example.com', 
                          :password => 'yourpass')

  gmail.deliver(:to => 'friend@example.com', 
                :subject => 'hello friend',
                :body => 'omgyay')

Here is one implementation:

require 'net/smtp'
require 'rubygems'
require 'tlsmail'
  
Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_PEER)
  
class GmailSender
  SMTP_ADDR = 'smtp.gmail.com'
  
  def initialize(opts = {})
    unless opts[:login] && opts[:password]
      raise ArgumentError.new("provide a login and password")
    end
    @login    = opts[:login]
    @password = opts[:password]
    @domain   = @login[/@(.+)$/,1]
  end

  
  def deliver(opts = {})
    @recipients = opts[:to]
    @subject = opts[:subject]
    @body = opts[:body]
    smtp_args = [SMTP_ADDR, 25, @domain, @login, @password, :login]
    Net::SMTP.start(*smtp_args) do |smtp|
      status = smtp.send_message message, @login, @recipients 
      puts status
    end
  end

  private

  def message
<<-EOS
FROM: #{@login}
TO: #{@recipients.is_a?(Array) ? @recipients.join(', ') : @recipients}
SUBJECT: #{@subject}

#{@body}
EOS
  end
end

Turn this into a local gem and you are ready to write command line email hacks to your heart’s content.

All CLZ Posts

Hide this
Joypad Banner