ruby-on-rails-3actionmaileremail-headersrfc5322

Set the Message-ID mail header in Rails3 / ActionMailer


I would like to alter the Message-ID header that is in the header portion of an email sent from a Ruby on Rails v3 application using ActionMailer.

I am using Sendmail on localhost for mail delivery.

Do I configure this in Sendmail or ActionMailer?

Where do I configure this (if it is ActionMailer): a file in config/ folder or a file in app/mailers/ folder?


Solution

  • I figured this out. The easiest way to do is to use the default method at the top of the mailer class file.

    Example:

    require 'digest/sha2'
    class UserMailer < ActionMailer::Base
      default "Message-ID"=>"#{Digest::SHA2.hexdigest(Time.now.to_i.to_s)}@yourdomain.com"
    
      # ... the rest of your mailer class
    end
    

    However, I found this difficult to test, so I wrote a private method and used the sent_at time instead of Time.now:

    def message_id_in_header(sent_at=Time.now)
      headers["Message-ID"] = "#{Digest::SHA2.hexdigest(sent_at.to_i.to_s)}@yourdomain.com"
    end
    

    And I simply called that method before calling the mail method. This made it easy to pass a sent_at parameter from my test and verify a match in email.encoded.