Skip to content

Instantly share code, notes, and snippets.

@prestia
Created Apr 11, 2012
Embed
What would you like to do?
A simple, gem-free Ruby method for sending Gmail

After digging through countless posts trying to find a quick and easy way to send Gmail using Ruby, I eventually had to come up with something on my own. Most solutions online require installing Gmail-specific gems (unnecessary) or are based on versions of Ruby prior to 1.8.7, which added native TLS support to Net::SMTP. The following code is based on a great little method by Jerod Santo, but has been expanded to work with Gmail and Net::SMTP's native TLS support:

require 'net/smtp'

def send_gmail(to,opts={})
  opts[:server]     ||='smtp.gmail.com'
  opts[:port]       ||= 587
  opts[:from_dom]   ||='<your_domain>'
  opts[:login]      ||='<your_login>'
  opts[:pass]       ||='<your_password>'
  opts[:auth_type]  ||= :plain
  opts[:from]       ||='<your_email>'
  opts[:from_alias] ||='<your_name>'
  opts[:subject]    ||='Default subject.'
  opts[:body]       ||='Default body.'

  msg = <<EOF
From: #{opts[:from_alias]} <#{opts[:from]}
To: <#{to}>
Subject: #{opts[:subject]}
	
#{opts[:body]}
EOF

  smtp = Net::SMTP.new opts[:server], opts[:port]
  smtp.enable_starttls
  smtp.start(opts[:from_dom], opts[:login], opts[:pass], opts[:auth_type]) do |smtp|
    smtp.send_message msg, opts[:from], to
  end
end

To use the method, first fill in the defaults for opts[:from_dom], opts[:login], opts[:pass], opts[:from], opts[:from_alias], and any others you would like to change. After that, everything except the to argument is optional. Here are a few sample invocations:

# Send an email to person@domain.com with the default subject line and messagebody:
send_gmail "person@domain.com"

# Send an email to person@domain.com with a custom subject line and message body:
send_gmail "person@domain.com", :subject => "This is the subject line", :body => "Hello, world! This is the body of my message."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment