lib/railgun/mailer.rb in mailgun-ruby-1.2.4 vs lib/railgun/mailer.rb in mailgun-ruby-1.2.5

- old
+ new

@@ -9,11 +9,11 @@ # 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 reply-to mime-version ] + IGNORED_HEADERS = %w[ to from subject reply-to mime-version template ] # [Hash] config -> # Requires *at least* `api_key` and `domain` keys. attr_accessor :config, :domain, :settings @@ -45,12 +45,15 @@ @mg_client.enable_test_mode! end end def deliver!(mail) + @mg_domain = set_mg_domain(mail) + mail[:domain] = nil if mail[:domain].present? + mg_message = Railgun.transform_for_mailgun(mail) - response = @mg_client.send_message(@domain, mg_message) + response = @mg_client.send_message(@mg_domain, mg_message) if response.code == 200 then mg_id = response.to_h['id'] mail.message_id = mg_id end @@ -59,10 +62,18 @@ def mailgun_client @mg_client end + private + + # Set @mg_domain from mail[:domain] header if present, then remove it to prevent being sent. + def set_mg_domain(mail) + return mail[:domain].value if mail[:domain] + domain + end + end module_function # Performs a series of transformations on the `mailgun*` attributes. @@ -76,20 +87,20 @@ # # @return [Hash] transformed message hash def transform_for_mailgun(mail) message = build_message_object(mail) - # v:* attributes (variables) - mail.mailgun_variables.try(:each) do |k, v| - message["v:#{k}"] = JSON.dump(v) - end - # o:* attributes (options) mail.mailgun_options.try(:each) do |k, v| message["o:#{k}"] = v.dup end + # t:* attributes (options) + mail.mailgun_template_variables.try(:each) do |k, v| + message["t:#{k}"] = v.dup + 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 @@ -151,10 +162,11 @@ def build_message_object(mail) mb = Mailgun::MessageBuilder.new mb.from mail[:from] mb.reply_to(mail[:reply_to].to_s) if mail[:reply_to].present? + mb.template(mail[:template].to_s) if mail[:template].present? mb.subject mail.subject mb.body_html extract_body_html(mail) mb.body_text extract_body_text(mail) [:to, :cc, :bcc].each do |rcpt_type| @@ -170,10 +182,15 @@ when Mail::Field mb.add_recipient rcpt_type.to_s, addrs.to_s end end + # v:* attributes (variables) + mail.mailgun_variables.try(:each) do |name, value| + mb.variable(name, value) + end + return mb.message if mail.attachments.empty? mail.attachments.each do |attach| attach = Attachment.new(attach, encoding: 'ascii-8bit', inline: attach.inline?) attach.attach_to_message! mb @@ -231,7 +248,6 @@ # @return [Mail::Message] mail message with its content-type = text/html def retrieve_html_part(mail) return mail.html_part if mail.multipart? (mail.mime_type =~ /^text\/html$/i) && mail end - end