首页 > 解决方案 > 是否可以在 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对象而不是提取其内容,检查它是否是多部分等?

标签: ruby-on-railsemailactionmaileraction-mailbox

解决方案


尝试一下。在您的方法中重用邮件对象process并自己直接传递消息。您需要访问 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

这是如何工作的:

在幕后 Mailers 只是在调用deliver一个Mail对象来发送电子邮件。ActionMailer::MessageDelivery如果您想看到它的实际效果,您可以仔细阅读。我们只是在这里直接使用该功能。

我建议不要在这种情况下使用 Mailers,因为将原始邮件对象中的所有字段复制到邮件程序的邮件对象需要大量的试验和错误。

需要注意的一件事:重新传递消息时标头保持不变,因此类似的事情Message-ID仍然是相同的(这可能是也可能不是问题,只是需要考虑的事情)。

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


推荐阅读