问题描述
在电子邮件中,看起来像从或到字段可以包含一个或多个地址,每个地址可以像[email protected]
或John D Jr< [email protected]>
所以一个从字段可以看起来像以下任何一种:
[email protected]
pre>
a @ a .com,Bob Blue< [email protected]
Abe Allen< [email protected]> [email protected]
Abe Allen< [email protected]> Bob Blue< [email protected]>
Abe Allen< [email protected]> Bob Blue< [email protected]> [email protected]
等等。
我想解析这些字段,提取每个地址的电子邮件,如果它有效,以及名称(如果有)。由于我不熟悉电子邮件标准,我可能会缺少一些可以看到什么地址字段的情况。有没有一个Ruby库可以做到这一点?
解决方案是的,有一个宝石为此;它被称为 。
require'mail'
addresses = []
raw_addresses = Mail :: AddressList.new(Abe Allen< [email protected]> Bob Blue < [email protected]> [email protected])
raw_addresses.addresses.each do | a |
address = {}
address [:address] = a.address
address [:name] = a.display_name如果a.display_name.present?
地址<<<地址
end
In an email, it looks like a "from" or "to" field can contain one or more addresses, each address can be like
"[email protected]"
or"John D Jr <[email protected]>"
So a "from" field can look like any of the following:
"[email protected]" "[email protected], Bob Blue <[email protected]>" "Abe Allen <[email protected]>, [email protected]" "Abe Allen <[email protected]>, Bob Blue <[email protected]>" "Abe Allen <[email protected]>, Bob Blue <[email protected]>, [email protected]"
and so on.
I want to parse these fields, extracting each address' email if it's valid, and the name if it's present. Since I'm not familiar with the email standard, I may be missing some cases of what address fields can look like. Is there a Ruby library that can do this?
解决方案Yes, there's a gem for this; it's called mail.
require 'mail' addresses = [] raw_addresses = Mail::AddressList.new("Abe Allen <[email protected]>, Bob Blue <[email protected]>, [email protected]") raw_addresses.addresses.each do |a| address = {} address[:address] = a.address address[:name] = a.display_name if a.display_name.present? addresses << address end
这篇关于解析“来自”的电子邮件地址和“至” Ruby中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!