Skip to content

Instantly share code, notes, and snippets.

@poiyzy
Last active December 14, 2015 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poiyzy/5029528 to your computer and use it in GitHub Desktop.
Save poiyzy/5029528 to your computer and use it in GitHub Desktop.
Mailgun Demo
class Api::BouncedMailsController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
if verify(ENV["mailgun_api_key"], params[:token], params[:timestamp], params[:signature])
user = User.find_by_email(params[:recipient])
if user && params[:event] == "bounced"
user.lock!
end
head(200)
end
end
private
def verify(api_key, token, timestamp, signature)
signature == OpenSSL::HMAC.hexdigest(
OpenSSL::Digest::Digest.new('sha256'),
api_key,
'%s%s' % [timestamp, token])
end
end
class Api::IncomingMessagesController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
user = User.where(email: params['sender']).first
text = params["stripped-text"]
if user && text.present?
user.issues.create content: text
end
head(200)
end
end
class MailgunGateway
include Rails.application.routes.url_helpers
def send_batch_message(users)
RestClient.post(messaging_api_end_point,
from: "Mailgun Demo <billing@#{ENV["mailgun_domain_name"]}>",
to: users.map(&:email).join(", "),
subject: "Monthly Billing Info",
html: billing_info_text,
:"h:Reply-To" => "billing@#{ENV["mailgun_domain_name"]}",
:"recipient-variables" => recipient_variables(billing_recipients)
)
end
private
def api_key
@api_key ||= ENV["mailgun_api_key"]
end
def messaging_api_end_point
@messaging_api_end_piont ||= "https://api:#{api_key}@api.mailgun.net/v2/#{ENV["mailgun_domain_name"]}/messages"
end
def billing_recipients
@users ||= User.where(locked: false)
end
def recipient_variables(recipients)
vars = recipients.map do |recipient|
"\"#{recipient.email}\": {\"name\":\"#{recipient.fullname}\"}"
end
"{#{vars.join(', ')}}"
end
def billing_info_text
<<-EMAIL
<html><body>
Hi %recipient.name%,
<p>
Your bill for the current month is now available, please click on
<br/>
#{billing_url}
<br/>
to see details.
</p>
<p>Reply to this email directly</p>
</body></html>
EMAIL
end
end
desc "This task is called by the Heroku scheduler add-on"
task :send_billing_info => :environment do
if DateTime.now.mday == 1
User.where(locked: false).find_in_batches(batch_size: 1000) do |group|
MailgunGateway.new.send_batch_message(group)
end
end
end
class User < ActiveRecord::Base
def lock!
self.locked = true
save(validate: false)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment