lib/sendgrid_actionmailer.rb in sendgrid-actionmailer-3.1.1 vs lib/sendgrid_actionmailer.rb in sendgrid-actionmailer-3.2.0
- old
+ new
@@ -12,25 +12,26 @@
DEFAULTS = {
raise_delivery_errors: false
}.freeze
- attr_accessor :settings, :api_key
+ attr_accessor :settings, :options
def initialize(params = {})
self.settings = DEFAULTS.merge(params)
end
def deliver!(mail)
+ self.options = {}
sendgrid_mail = Mail.new.tap do |m|
m.from = to_email(mail.from)
m.reply_to = to_email(mail.reply_to)
m.subject = mail.subject || ""
end
add_personalizations(sendgrid_mail, mail)
- add_api_key(sendgrid_mail, mail)
+ add_options(sendgrid_mail, mail)
add_content(sendgrid_mail, mail)
add_send_options(sendgrid_mail, mail)
add_mail_settings(sendgrid_mail, mail)
add_tracking_settings(sendgrid_mail, mail)
@@ -43,12 +44,18 @@
settings[:return_response] ? response : self
end
private
+ def client_options
+ options.dup
+ .select { |key, value| key.to_s.match(/(api_key|host|request_headers|version|impersonate_subuser)/) }
+ .merge(http_options: settings.fetch(:http_options, {}))
+ end
+
def client
- @client = SendGrid::API.new(api_key: api_key).client
+ @client = SendGrid::API.new(**client_options).client
end
# type should be either :plain or :html
def to_content(type, value)
Content.new(type: "text/#{type}", value: value)
@@ -144,14 +151,14 @@
content_disp = message.header[:content_disposition]
return unless content_disp.respond_to?(:disposition_type)
content_disp.disposition_type
end
- def add_api_key(sendgrid_mail, mail)
- self.api_key = settings.fetch(:api_key)
- if mail['delivery-method-options'] && mail['delivery-method-options'].value.include?('api_key')
- self.api_key = mail['delivery-method-options'].unparsed_value['api_key']
+ def add_options(sendgrid_mail, mail)
+ self.options.merge!(**self.class.transform_keys(self.settings, &:to_sym))
+ if !!(mail['delivery-method-options'])
+ self.options.merge!(**self.class.transform_keys(mail['delivery-method-options'].unparsed_value , &:to_sym))
end
end
def add_attachments(sendgrid_mail, mail)
mail.attachments.each do |part|
@@ -284,12 +291,10 @@
def perform_send_request(email)
result = client.mail._('send').post(request_body: email.to_json) # ლ(ಠ益ಠლ) that API
if result.status_code && result.status_code.start_with?('4')
- message = !(result.body.empty?) ? JSON.parse(result.body).fetch('errors').pop.fetch('message') : 'Sendgrid API Error'
- full_message = "Sendgrid delivery failed with #{result.status_code} #{message}"
-
+ full_message = "Sendgrid delivery failed with #{result.status_code}: #{result.body}"
settings[:raise_delivery_errors] ? raise(SendgridDeliveryError, full_message) : warn(full_message)
end
result
end