ActiveCampaign/postmark-rails

Cannot send metadata with #deliver_later

hnatt opened this issue · 1 comments

hnatt commented

Email sending wiki page says that metadata needs to be assigned outside the mail method:

class TestMailer < ActionMailer::Base

  def message_with_metadata
    metadata['foo'] = 'bar'
    mail(
      :subject              => 'meta hello',
      :to                   => 'sheldon@bigbangtheory.com',
      :from                 => 'leonard@bigbangtheory.com'
    )
  end

end

But when I try to deliver such message asynchronously, ActionMailer raises an error:

irb(main):060:0> mail.deliver_later
Traceback (most recent call last):
        1: from (irb):60
RuntimeError (You've accessed the message before asking to deliver it later, so you may have made local changes that would be silently lost if we enqueued a job to deliver it. Why? Only the mailer method *arguments* are passed with the delivery job! Do not access the message in any way if you mean to deliver it later. Workarounds: 1. don't touch the message before calling #deliver_later, 2. only touch the message *within your mailer method*, or 3. use a custom Active Job instead of #deliver_later.)

I tried different ways of doing it, outside using a custom Active Job, and so far it seems I can either have a working metadata section, or #deliver_later, but not both. Am I missing something?

hnatt commented

Turns out, I was missing something, and it was the understanding of how ActionMailer works. We have some logic layers around ActionMailer and I was trying to assign metadata from outside the mailer method. Which is exactly what the error message is saying. When invoked from inside the mailer method, like in the example, then deliver_later works and metadata is submitted.