Skip to content

Instantly share code, notes, and snippets.

@nirix
Created January 24, 2012 22:41
Show Gist options
  • Save nirix/1673189 to your computer and use it in GitHub Desktop.
Save nirix/1673189 to your computer and use it in GitHub Desktop.
Hack for sending Emails using Amazon SES without having to depend on Mail.
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