英文:
NoMethodError when "to" contains a name with unparsable characters
问题
以下是您要翻译的内容:
We get people's names from a third party source, some of the last names contain a department suffix such as "(R&D)"
. When trying to send email, via ActionMailer, we get a NoMethodError
error originating in the mail gem.
It can be reproduced without ActionMailer as follows:
to = "Kris Leech <kris@example.com>"
mail = Mail.new { to(to) }
mail[:to].addrs # => [#<Mail::Address]
to = "Kris Leech [TECH] <kris@example.com>"
mail = Mail.new { to(to) }
mail[:to].addrs # => NoMethodError: undefined method 'addrs' for Mail::UnstructuredField
The presence of the square brackets cause Mail::UnstructuredField
, which does not respond to addrs
, to be returned instead of Mail::StructuredField
.
We can see that there is a parse error:
mail[:to].errors # => [["To", "Kris Leech [TECH] <kris.leech@example.com>", #<Mail::Field::IncompleteParseError: Mail::AddressList can not parse |Kris Leech [TECH] <kris@example.com>|: Only able to parse up to "Kris Leech ">]]
How do I escape or otherwise correct the name part of the "to"?
英文:
We get people's names from a third party source, some of the last names contain a department suffix such as "(R&D)"
. When trying to send email, via ActionMailer, we get a NoMethodError
error originating in the mail gem.
It can be reproduced without ActionMailer as follows:
to = "Kris Leech <kris@example.com>"
mail = Mail.new { to(to) }
mail[:to].addrs # => [#<Mail::Address]
to = "Kris Leech [TECH] <kris@example.com>"
mail = Mail.new { to(to) }
mail[:to].addrs # => NoMethodError: undefined method `addrs' for Mail::UnstructuredField
The presence of the square brackets cause Mail::UnstructuredField
, which does not respond to addrs
, to be returned instead of Mail::StructuredField
.
We can see that there is a parse error:
mail[:to].errors # => [["To", "Kris Leech [TECH] <kris.leech@example.com>", #<Mail::Field::IncompleteParseError: Mail::AddressList can not parse |Kris Leech [TECH] <kris@example.com>|: Only able to parse up to "Kris Leech ">]]
How do I escape or otherwise correct the name part of the "to"?
答案1
得分: 2
根据规范,名称部分在包含保留字符时必须加引号。
这在Mail::Utilities中实现。
因此,我们可以像这样“引用”名称部分:
QuoteName = Class.new do
extend Mail::Utilities
def self.call(name)
quote_phrase(name)
end
end
to = "#{QuoteName.('Kris Leech [TECH]')} <kris@example.com>"
mail = Mail.new { to(to) }
mail[:to].addrs # => [#<Mail::Address]
英文:
As per the specification the name part, when it contains reserved characters, must be quoted.
This is implemented in Mail::Utilities.
So we can "quote" the name part as such:
QuoteName = Class.new do
extend Mail::Utilities
def self.call(name)
quote_phrase(name)
end
end
to = "#{QuoteName.('Kris Leech [TECH]')} <kris@example.com>"
mail = Mail.new { to(to) }
mail[:to].addrs # => [#<Mail::Address]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论