Created
January 24, 2012 22:41
Hack for sending Emails using Amazon SES without having to depend on Mail.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'httparty' | |
require 'hmac-sha2' | |
require 'base64' | |
require 'cgi' | |
module Amazon | |
module SES | |
OPTIONS = { | |
:access_key => '...', | |
:secret_key => '...' | |
} | |
class Email | |
include HTTParty | |
format :xml | |
base_uri 'https://email.us-east-1.amazonaws.com' | |
attr_accessor :from | |
attr_accessor :to | |
attr_accessor :subject | |
attr_accessor :body | |
def initialize(opts = {}) | |
opts.each { |k, v| send("#{k}=", v) if respond_to?("#{k}=") } | |
end | |
def deliver | |
time = Time.now | |
url_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z') | |
sig_time = time.gmtime.strftime('%a, %d %b %Y %H:%M:%S GMT') | |
options = { | |
:headers => { | |
'X-Amzn-Authorization' => signature(sig_time), | |
'Date' => sig_time | |
}, | |
:query => { | |
:Action => 'SendEmail', | |
:Source => from, | |
:'Destination.ToAddresses.member.1' => to, | |
:'Message.Subject.Data' => subject, | |
:'Message.Body.Text.Data' => body, | |
:AWSAccessKeyId => OPTIONS[:access_key], | |
:Timestamp => url_time, | |
:Version => '2010-12-01' | |
} | |
} | |
response = self.class.post('/', options) | |
if response.key?('ErrorResponse') | |
msg = response.parsed_response['ErrorResponse']['Error']['Message'] | |
raise "Failed to send the Email: #{msg}" | |
else | |
return response.parsed_response['SendEmailResponse'] \ | |
['SendEmailResult']['MessageId'] | |
end | |
end | |
def signature(time) | |
hash = HMAC::SHA256.new(OPTIONS[:secret_key]) | |
hash.update(time) | |
hash = Base64.encode64(hash.digest).chomp | |
return "AWS3-HTTPS AWSAccessKey=#{OPTIONS[:access_key]}, " \ | |
"Signature=#{hash}, Algorithm=HmacSHA256" | |
end | |
end # Email | |
end # SES | |
end # Amazon | |
email = Amazon::SES::Email.new( | |
:from => '...', | |
:to => '...', | |
:subject => 'Testing Ruby Hacks', | |
:body => 'Lorem ipsum dolor sit amet' | |
) | |
p email.deliver |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment