Rails ActionMailer-格式化发件人和收件人姓名/电子邮件地址

在使用 ActionMailer 时,是否有方法指定发件人和收件人信息的电子邮件和名称?

通常你会这么做:

@recipients   = "#{user.email}"
@from         = "info@mycompany.com"
@subject      = "Hi"
@content_type = "text/html"

但是,我还想指定名称—— MyCompany <info@mycompany.com>John Doe <john.doe@mycompany>

有办法吗?

45895 次浏览
@recipients   = "\"#{user.name}\" <#{user.email}>"
@from         = "\"MyCompany\" <info@mycompany.com>"

在 Rails 2.3.3中,在 ActionMailer 中引入了一个 bug。你可以看到票在这里 Ticket #2340。它在2.3-Stability 和 master 中得到了解决,因此它将在3.x 和2.3.6中得到修复。

为了修复2.3. * 中的问题,可以使用票据注释中提供的代码:

module ActionMailer
class Base
def perform_delivery_smtp(mail)
destinations = mail.destinations
mail.ready_to_send
sender = (mail['return-path'] && mail['return-path'].spec) || Array(mail.from).first


smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
smtp.enable_starttls_auto if smtp_settings[:enable_starttls_auto] && smtp.respond_to?(:enable_starttls_auto)
smtp.start(smtp_settings[:domain], smtp_settings[:user_name], smtp_settings[:password],
smtp_settings[:authentication]) do |smtp|
smtp.sendmail(mail.encoded, sender, destinations)
end
end
end
end

另一个令人恼火的方面是,至少在新的 AR 格式中,要记住在类级别上调用“ default”。引用仅为实例的例程会导致它无声地失败,并在您尝试使用它时给出:

 NoMethodError: undefined method `new_post' for Notifier:Class

Here's what I ended up using:

def self.named_email(name,email) "\"#{name}\" <#{email}>" end
default :from => named_email(user.name, user.email)

在 Rails3中,我在每个环境中都放置了以下内容

ActionMailer::Base.default :from => "Company Name <no-reply@production-server.ca>"

在 Rails3中,围绕公司名称设置报价对我来说不起作用。

如果您使用用户输入的名称和电子邮件,那么除非您非常仔细地验证或转义名称和电子邮件,否则您可以通过简单地连接字符串来得到一个无效的 From 头。这里有一个安全的方法:

require 'mail'
address = Mail::Address.new email # ex: "john@example.com"
address.display_name = name.dup   # ex: "John Doe"
# Set the From or Reply-To header to the following:
address.format # returns "John Doe <john@example.com>"

The version I like to use of this is

%`"#{account.full_name}" <#{account.email}>`

都是回勾。

更新

你也可以把它改成

%|"#{account.full_name}" <#{account.email}>|
%\"#{account.full_name}" <#{account.email}>\
%^"#{account.full_name}" <#{account.email}>^
%["#{account.full_name}" <#{account.email}>]

了解更多关于字符串文字的信息。

因为 Rails 6.1ActionMailer::Base上有一个新的方便的辅助方法:

ActionMailer::Base.email_address_with_name("test@test.com", "John Test with Quotes <'")
=> "\"John Test with Quotes <'\" <test@test.com>"

在 Mailer 中,不需要类名即可访问:

mail to: email_address_with_name(user.email, user.name), ...

Under the hood it uses the Mail::Address like in the top answer.