class FlowmailerRails::Mailer
Constants
- API_ENDPOINT
- OAUTH_ENDPOINT
Attributes
settings[RW]
Public Class Methods
new(values)
click to toggle source
# File lib/flowmailer_rails/mailer.rb, line 19 def initialize(values) self.settings = {}.merge!(values) end
Public Instance Methods
deliver!(rails_mail)
click to toggle source
# File lib/flowmailer_rails/mailer.rb, line 23 def deliver!(rails_mail) MailConverter.new(rails_mail).recipients_as_json.each do |json| response = submit_message(json) rails_mail.message_id = response.headers["location"].split("/").last end end
Private Instance Methods
access_token()
click to toggle source
# File lib/flowmailer_rails/mailer.rb, line 78 def access_token if settings[:access_token] settings[:access_token].call else @access_token ||= fetch_new_access_token end end
api_client()
click to toggle source
# File lib/flowmailer_rails/mailer.rb, line 70 def api_client @api_client ||= Faraday.new(url: API_ENDPOINT) { |conn| conn.request :json conn.response :json, content_type: /\bjson$/ conn.adapter Faraday.default_adapter } end
fetch_new_access_token()
click to toggle source
# File lib/flowmailer_rails/mailer.rb, line 86 def fetch_new_access_token if settings[:fetch_new_access_token] settings[:fetch_new_access_token].call else response = oauth_client.post( "oauth/token", client_id: settings[:client_id], client_secret: settings[:client_secret], grant_type: "client_credentials", scope: "api" ) if response.success? @access_token = response.body["access_token"] else raise NoAccessTokenError, response.body end end end
handle_failure(response)
click to toggle source
# File lib/flowmailer_rails/mailer.rb, line 58 def handle_failure(response) return if response.success? raise ExpiredAccessTokenError if response.status == 401 too_big_error = response.body&.[]("allErrors")&.find { |error| error["code"] == "message.toobig" } raise TooBigMessageError, too_big_error["defaultMessage"] if too_big_error.present? raise DeliveryError, response.body end
oauth_client()
click to toggle source
# File lib/flowmailer_rails/mailer.rb, line 105 def oauth_client @oauth_client ||= Faraday.new(url: OAUTH_ENDPOINT) { |conn| conn.request :url_encoded conn.response :json, content_type: /\bjson$/ conn.adapter Faraday.default_adapter } end
path()
click to toggle source
# File lib/flowmailer_rails/mailer.rb, line 32 def path "#{settings[:account_id]}/messages/submit" end
submit_message(json)
click to toggle source
# File lib/flowmailer_rails/mailer.rb, line 40 def submit_message(json) retries = 0 begin response = api_client.post(path, json, authorization_header) handle_failure(response) rescue ExpiredAccessTokenError if (retries += 1) <= 3 fetch_new_access_token retry else raise end end response end