是否可以在 Action Mailer 中转发邮件对象

Is it possible to forward the mail object in Action Mailer

我们目前允许用户将电子邮件发送至 username@parse.example.com,从而让用户在不看到彼此实际电子邮件地址的情况下相互发送电子邮件(双盲),效果很好。

class ForwardsMailbox < ApplicationMailbox
  before_processing :ensure_users
 
  def process
    content = mail.multipart? ? mail.parts.first.body.decoded : mail.decoded
    UserMailer.with(sender: sender, recipient: recipient, subject: mail.subject, content: content).forward_email.deliver_later
  end
 
  private 
  def sender
    @sender ||= User.find_by(email: mail.from.first)
  end
  def recipient
    @recipient ||= User.find_by(username: mail.to.first.split('@').first)
  end
  def ensure_users
    bounce_with UserMailer.invalid_user(inbound_email) if sender.nil? or recipient.nil?
  end
end

是否可以转发整个 mail 对象而不是提取其内容、检查它是否是多部分等?

尝试一下。在您的 process 方法中重复使用邮件 object 并自己直接发送邮件。您需要进入 ActionMailer 以正确配置您的投递方式,但我相信它会起作用。

def process
  mail.to = sender.email
  mail.from = recipient...
  ActionMailer::Base.wrap_delivery_behavior(mail) # this sets delivery to use what we specified in our rails config.
  mail.deliver # This delivers our email to the smtp server / API
end

这是如何工作的:

在幕后,邮件程序只是在 Mail object 上调用 deliver 来发送电子邮件。如果您想实际查看,可以仔细阅读 ActionMailer::MessageDelivery。我们只是在这里直接使用该功能。

在这种情况下,我建议不要使用 Mailers,因为将原始邮件 object 中的所有字段复制到邮寄者的邮件 object 将需要大量试验,并且错误。

需要注意的一件事:headers 在消息为 re-delivered 时保持不变,因此 Message-ID 之类的内容仍然相同(这可能是问题,也可能不是问题,只是需要考虑的事情)。

最后,如果您像我一样担心 deliver 会阻塞对 API/SMTP 服务器的调用,请不用担心!看起来 ActionMailbox 已经确保 process 方法通过 ActiveJob 运行,因此您不必担心 SMTP/API 请求需要一段时间并阻止 Web 请求(参见 ActionMailbox guides) .