Skip to content

Instantly share code, notes, and snippets.

@arthurnn
Created December 17, 2018 16:50
Show Gist options
  • Save arthurnn/269c759735cb1be572519f3a1459fac3 to your computer and use it in GitHub Desktop.
Save arthurnn/269c759735cb1be572519f3a1459fac3 to your computer and use it in GitHub Desktop.
Sendgrid mailer
# frozen_string_literal: true
require 'sendgrid-ruby'
require 'sendgrid_mailer/mailer'
class SendgridDelivery
class InvalidEmail < StandardError; end
def initialize(*)
end
def api
unless api_key = ENV['SENDGRID_API_KEY']
raise 'Sendgrid api key is not present. Emails cannot be delivered '
end
SendGrid::API.new(api_key: api_key)
end
def deliver!(mail)
email = SendGrid::Mail.new
email.from =
SendGrid::Email.new(email: mail[:from].value,
name: mail[:from_name]&.value)
email.subject = mail[:subject]&.value
if mail['template-id']
email.template_id = mail['template-id'].value
elsif mail.body
email.add_content(SendGrid::Content.new(type: mail.mime_type,
value: mail.body.decoded))
end
personalization = SendGrid::Personalization.new
personalization.add_to(SendGrid::Email.new(email: mail[:to].value,
name: mail[:to_name]&.value))
if bccs = mail[:bcc]&.value
Array(bccs).each do |bcc|
personalization.add_bcc(SendGrid::Email.new(email: bcc))
end
end
if subs = mail.sendgrid_substitutions
subs.each do |key, value|
personalization.add_substitution(
SendGrid::Substitution.new(key: key.to_s, value: value.to_s)
)
end
end
if categories = mail.sendgrid_categories
categories.each do |name|
email.add_category(SendGrid::Category.new(name: name))
end
end
email.add_personalization(personalization)
mail.attachments.each do |item|
attachment = SendGrid::Attachment.new
attachment.content = Base64.strict_encode64(item.decoded)
attachment.type = item.mime_type
attachment.filename = item.filename
attachment.disposition = 'attachment'
email.add_attachment(attachment)
end
Rails.logger.debug('Sending email using SendGrid API:')
Rails.logger.debug(email.to_json)
response = api.client.mail._('send').post(request_body: email.to_json)
Rails.logger.debug("Response code: #{response.status_code}\nResponse body: #{response.body}")
unless (200..299).include?(Integer(response.status_code))
raise InvalidEmail,
"Bad email. Response body: #{response.body}. Input was: #{email.to_json}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment