Skip to content

[includes solution] ActionMailer Email Preview ignoring optional date header #49788

@allisonphillips

Description

@allisonphillips

My work requires total isolation of our GH accounts so I can't put up a PR for this right now / am not sure when I will have the bandwidth to do so, but if anyone wants an easy win:

Steps to reproduce

ActionMailer::Base#mail accepts a :date header argument, but the rails mailers email template doesn't check the date header and always renders Time.current.rfc2822

class MyMailerPreview < ActionMailer::Preview
  def preview
    mail = MailKlass.find(params[:id])

    MyMailer.view_sent(mail)
  end
end

class MyMailer < ActionMailer::Base
  def view_sent(email)
    mail(
      to: email.email,
      subject: email.subject,
      date: email.sent_at
    ) do |format|
      format.html { render email.template }
    end
  end
end

My use case is previewing an email that was already sent.

Expected behavior

ActionMailer template header section should render the value of @mail.header['date'] (from mail(date: some_timestamp)) if the header is present

Actual behavior

Previewed emails always render the result of Time.current.rfc2822 without checking for the presence of @email.header['date']

Solution

Replace this

<dd id="date"><%= Time.current.rfc2822 %></dd>

with this:

    <dd id="date"><%= @email.header['date'] || Time.current.rfc2822 %></dd>

System configuration

Rails version:
7x
Ruby version:
3.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions