Monday, October 11, 2010

Easy Email with SendGrid

In order to get up and running with email quickly and painlessly, I have been using the Heroku SendGrid plugin. Heroku creates some environment variables for use with your mail-library of choice when you install sendgrid:free. The problem with this is that you can't use these locally without setting them in your environment explicitly. Luckily you can work around this by referencing a file not in version control containing your sendgrid username and password, etc. Like so:

# Load private passwords for local development
# This file is not checked into version control and is used to store account information for development
if File.exist?("private_env.yaml")
YAML.load_file("private_env.yaml").each do |key,val|
ENV[key] = val
end
end

Then create the yaml file referenced:

---
SENDGRID_DOMAIN:   localhost.localdomain # sordina.net
SENDGRID_PASSWORD: XXXXXX
SENDGRID_USERNAME: XXXXXX@heroku.com
 
In order to determine these variables, just use the following command in your application:

heroku config -long

Now you are able to use the environment variables to send email with (in this example) Pony:


post '/contact' do
Pony.mail(
:to          => 'maydwell+sordina@gmail.com',
:from        => params[:email],
:subject     => "sordina.net feedback from [#{params[:name]}].",
:body        => params[:comment],

:via         => :smtp,
:via_options => {

:address        => 'smtp.sendgrid.net',
:port           => '25',
:authentication => :plain,
:user_name      => ENV['SENDGRID_USERNAME'],
:password       => ENV['SENDGRID_PASSWORD'],
:domain         => ENV['SENDGRID_DOMAIN']
})

redirect '/thanks'
end



Done!
 
 

No comments:

Post a Comment