lib/railgun/mailer.rb in mailgun-ruby-1.1.10 vs lib/railgun/mailer.rb in mailgun-ruby-1.1.11
- old
+ new
@@ -1,16 +1,20 @@
require 'action_mailer'
+require 'json'
require 'mailgun'
require 'rails'
require 'railgun/errors'
module Railgun
# Railgun::Mailer is an ActionMailer provider for sending mail through
# Mailgun.
class Mailer
+ # List of the headers that will be ignored when copying headers from `mail.header_fields`
+ IGNORED_HEADERS = %w[ to from subject ]
+
# [Hash] config ->
# Requires *at least* `api_key` and `domain` keys.
attr_accessor :config, :domain, :settings
# Initialize the Railgun mailer.
@@ -45,11 +49,11 @@
end
response
end
def mailgun_client
- @mg_obj
+ @mg_client
end
end
module_function
@@ -64,28 +68,61 @@
def transform_for_mailgun(mail)
message = build_message_object(mail)
# v:* attributes (variables)
mail.mailgun_variables.try(:each) do |k, v|
- message["v:#{k}"] = v
+ message["v:#{k}"] = JSON.dump(v)
end
# o:* attributes (options)
mail.mailgun_options.try(:each) do |k, v|
message["o:#{k}"] = v
end
+ # support for using ActionMailer's `headers()` inside of the mailer
+ # note: this will filter out parameters such as `from`, `to`, and so forth
+ # as they are accepted as POST parameters on the message endpoint.
+
+ msg_headers = Hash.new
+
# h:* attributes (headers)
mail.mailgun_headers.try(:each) do |k, v|
+ msg_headers[k] = v
+ end
+
+ mail.header_fields.each do |field|
+ msg_headers[field.name] = field.value
+ end
+
+ msg_headers.each do |k, v|
+ if Railgun::Mailer::IGNORED_HEADERS.include? k.downcase
+ Rails.logger.debug("[railgun] ignoring header (using envelope instead): #{k}")
+ next
+ end
+
+ # Cover cases like `cc`, `bcc` where parameters are valid
+ # headers BUT they are submitted as separate POST params
+ # and already exist on the message because of the call to
+ # `build_message_object`.
+ if message.include? k.downcase
+ Rails.logger.debug("[railgun] ignoring header (already set): #{k}")
+ next
+ end
+
message["h:#{k}"] = v
end
# recipient variables
message['recipient-variables'] = mail.mailgun_recipient_variables.to_json if mail.mailgun_recipient_variables
# reject blank values
message.delete_if do |k, v|
- v.nil? or (v.respond_to?(:empty) and v.empty?)
+ return true if v.nil?
+
+ # if it's an array remove empty elements
+ v.delete_if { |i| i.respond_to?(:empty?) && i.empty? } if v.is_a?(Array)
+
+ v.respond_to?(:empty?) && v.empty?
end
return message
end