我有一个第三方电子邮件集成库,我想用它来发送电子邮件作为我的一个用户。要发送电子邮件,我使用为每个用户保存的access_token
进行API调用。
为了仍然使用动作邮件,我创建了一个这样的自定义交付类:
module Mail
class CustomMailDelivery
attr_reader :settings
def initialize(settings)
@settings = settings
end
def deliver!(mail)
# use 3rd party client here
end
end
end
我在初始化器中配置它:
ActionMailer::Base.add_delivery_method :custom, Mail::CustomMailDelivery, {
app_id: ENV.fetch('3RDPARTY_APP_ID'),
app_secret: ENV.fetch('3RDPARTY_APP_SECRET'),
}
这允许我在每个邮件的基础上设置交付方法:
class LeadMailer < ApplicationMailer
self.delivery_method = :custom
...
end
问题是,我需要传递发送此消息的用户,所以我可以得到他们的access_token
。
我不想依赖于使用发件人的电子邮件地址获取EmailAccount
,因为这似乎可能会破坏道路(可能这个电子邮件地址可能与发送用户不同)。换句话说,我想明确地传递它,所以它很容易理解,我避免任何混淆。
有没有办法为自定义操作邮件传递类提供每邮件上下文?
我最终使用自定义邮件头传递此数据,我稍后在处理邮件时将其删除。
class CustomMailer < ApplicationMailer
self.delivery_method = :custom
attr_reader :sending_account
def mail(params)
raise 'You must call set_sending_account before calling mail.' unless sending_email_account
super(params.merge({
Mail::CustomMailDelivery::ACCOUNT_ID_HEADER => sending_account.id
}))
end
def set_sending_account(account)
@sending_account = account
end
end
这种方式需要此行为的邮件程序从此类继承子类并被强制提供自定义数据。
在交付类中,我从标题中提取了这个值:
module Mail
class CustomMailDelivery
attr_reader :settings
# we'll hijack email headers in order to pass over some required data from the mailer to this class
ACCOUNT_ID_HEADER = '__account_id'
def initialize(settings)
@settings = settings
end
def deliver!(mail)
account = account_for(mail)
client = third_party_api_client(account.access_token)
client.send_message(...)
end
private
def third_party_api_client(access_token)
# ...
end
def account_for(mail)
header_field = mail[ACCOUNT_ID_HEADER]
missing_account_id_header! unless header_field
email_account = Account.find(header_field.value)
# remove the header field so it doesn't show up in the actual email
mail[ACCOUNT_ID_HEADER] = nil
account
end
def missing_account_id_header!
raise "Missing required header: #{ACCOUNT_ID_HEADER}"
end
end
end
这个解决方案不是很优雅,但有效。
感谢您的想法,我使用register_observer
和register_interceptor
整理了一个较短的版本。
它基本上是相同的想法,除了你不需要重新定义太多的交付东西。您只需挂钩邮件工作流程即可。
首先,声明钩子:
ActionMailer::Base.register_observer(MailToActionEventObserver)
ActionMailer::Base.register_interceptor(MailToActionEventObserver)
然后,简单的部分是钩子是同一类内部的静态方法:
class MailToActionEventObserver
def self.delivered_email(mail)
# Here you can use @passed_argument because it is called just after
# self.delivering_email
end
def self.delivering_email(mail)
@passed_argument = mail['MY-PERSONAL-HEADER'].to_s
# Now remove the temporary header:
mail['MY-PERSONAL-HEADER'] = nil
end
end
现在,和你的答案@Ben一样,只需要将参数作为邮件中的标题传递:
def my_custom_mail
headers['MY-PERSONAL-HEADER'] = 'whatever-value'
mail(...)
end