Skip to content

Instantly share code, notes, and snippets.

@keithrbennett
Created September 3, 2012 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save keithrbennett/3605940 to your computer and use it in GitHub Desktop.
Save keithrbennett/3605940 to your computer and use it in GitHub Desktop.
Mail Script from Keith Bennett's Technical Blog
#!/usr/bin/env ruby
# Mails a file using GMail's SMTP Server.
# For illustrative purposes; error checking and testing intentionally omitted for brevity.
#
# Requirements:
# 1) the 'mail' gem must be installed
# 2) a file named 'pw.txt' containing the Google password must be present
# in the current directory.
#
# Ruby versions: tested on 1.9.3, 1.8.7, JRuby
#
# Keith Bennett
require 'rubygems' # Need this for Ruby 1.8
require 'mail'
ATTACHMENT_FILESPEC = 'attachment.txt'
File.open(ATTACHMENT_FILESPEC, 'w') do |file|
file << "Sample attachment text file, sent #{Time.now}\n"
end
# Used for GMail authentication and the 'from' header field.
def my_gmail_address
# Return your gmail address, e.g.:
'me@gmail.com'
end
# Used for 'to' header field
def recipients
# a single address or a comma separated list of email addresses, e.g.:
'mom@aol.com,fred@people.com'
end
# GMail password for SMTP authentication.
# Create a file named 'pw.txt' and put your password there in plain text.
# Not the best way to do this!
def password
File.read('pw.txt')
end
def body_text
"This message contains the following attachment: #{ATTACHMENT_FILESPEC}.\nSent #{Time.now}"
end
def subject_text
"Gmail-It Attached File: #{ATTACHMENT_FILESPEC}"
end
# This information could probably be put in the Mail.deliver block below,
# but it's here in case multiple mail calls are made.
Mail.defaults do
delivery_method :smtp, {
:address => "smtp.gmail.com",
:port => 587,
:domain => 'gmail.com',
:user_name => my_gmail_address,
:password => password,
:enable_starttls_auto => true }
end
puts "Delivering file: #{ATTACHMENT_FILESPEC} to #{recipients}."
Mail.deliver do
from my_gmail_address
to recipients
subject subject_text
body body_text
add_file ATTACHMENT_FILESPEC
end
puts "File #{ATTACHMENT_FILESPEC} sent."
puts "Check recipient email account(s) (#{recipients}) to verify success."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment