Created
June 8, 2012 08:44
-
-
Save kristianhellquist/2894535 to your computer and use it in GitHub Desktop.
Sendgrid usage
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
module Sendgrid | |
module Configuration | |
def self.included(klass) | |
klass.extend ClassMethods | |
end | |
def mail(headers = {}, &block) | |
headers['X-SMTPAPI'] = { category: calling_mailer_and_action.join("#") }.to_json | |
super(headers, &block) | |
end | |
protected | |
# Returns e.g. [ "FooMailer", "my_action" ] | |
# | |
# Thank you Joakim Kolsjö and Henrik Nyh! https://gist.github.com/2775581 | |
def calling_mailer_and_action | |
# The caller method gives the call chain in the format | |
# [ "app_mailer.rb:2 in `my_method'", "sub_mailer.rb:5 in `my_method'", script/rails:6 in `<main>"' ] | |
# Look for Mailer classes and pick the last one, at the bottom of the inheritance chain. | |
if caller_string = caller.grep(%r{/app/mailers/.+_mailer\.rb}).last | |
# Extract mailer name and action from that line. | |
mailer, action = caller_string.scan(%r{/app/mailers/(.+_mailer)\.rb:\d+:in `(.+)'}).flatten | |
[ mailer.camelize, action ] | |
end | |
end | |
module ClassMethods | |
# Makes it possible to use a different sendgrid account for a mailer | |
def sendgrid_credentials(username, password) | |
@sendgrid_username = username | |
@sendgrid_password = password | |
end | |
def delivery_method | |
use_sendgrid? ? :smtp : :test | |
end | |
def smtp_settings | |
{ | |
:address => "smtp.sendgrid.net", | |
:port => 587, | |
:enable_starttls_auto => true, | |
:user_name => @sendgrid_username, | |
:password => @sendgrid_password | |
} | |
end | |
protected | |
def use_sendgrid? | |
@sendgrid_username.present? && @sendgrid_password.present? | |
end | |
end | |
end | |
end | |
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 'sendgrid/configuration' | |
class PaymentMailer < ActionMailer::Base | |
include Sendgrid::Configuration | |
sendgrid_credentials AppConfig.sendgrid.username, AppConfig.sendgrid.password | |
default :from => '"Mynewsdesk" <[email protected]>' | |
def payment_success(user, payment) | |
@payment = payment | |
I18n.with_locale(user.locale) do | |
mail({ | |
:subject => I18n.t(:'mailer.payment_success.payment_success'), | |
:to => user.email | |
}) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment