[英]Parse email addresses for “from” and “to” fields in Ruby
In an email, it looks like a "from" or "to" field can contain one or more addresses, each address can be like "john@test.com"
or "John D Jr <john@test.com>"
在电子邮件中,看起来“from”或“to”字段可以包含一个或多个地址,每个地址可以像
"john@test.com"
或"John D Jr <john@test.com>"
So a "from" field can look like any of the following: 因此,“from”字段可能看起来像以下任何一种:
"a@a.com"
"a@a.com, Bob Blue <b@b.com>"
"Abe Allen <a@a.com>, b@b.com"
"Abe Allen <a@a.com>, Bob Blue <b@b.com>"
"Abe Allen <a@a.com>, Bob Blue <b@b.com>, c@c.com"
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?
是否有可以执行此操作的Ruby库?
Yes, there's a gem for this; 是的,这是一个宝石; it's called mail .
它被称为邮件 。
require 'mail'
addresses = []
raw_addresses = Mail::AddressList.new("Abe Allen <a@a.com>, Bob Blue <b@b.com>, c@c.com")
raw_addresses.addresses.each do |a|
address = {}
address[:address] = a.address
address[:name] = a.display_name if a.display_name.present?
addresses << address
end
Assuming your data follows the examples you gave, this should work: 假设您的数据遵循您提供的示例,这应该有效:
def extract_emails(string)
string.split(', ').map do |user_string|
if user_string.include? '<'
user_string =~ /^([^<]*)<([^>]*)>$/
{user: $1.strip, email: $2}
else
{user: nil, email: user_string}
end
end
end
extract_emails "a@a.com"
# => [{:user=>nil, :email=>"a@a.com"}]
extract_emails "a@a.com, Bob Blue <b@b.com>"
# => [{:user=>nil, :email=>"a@a.com"}, {:user=>"Bob Blue", :email=>"b@b.com"}]
extract_emails "Abe Allen <a@a.com>, b@b.com"
# => [{:user=>"Abe Allen", :email=>"a@a.com"}, {:user=>nil, :email=>"b@b.com"}]
extract_emails "Abe Allen <a@a.com>, Bob Blue <b@b.com>"
# => [{:user=>"Abe Allen", :email=>"a@a.com"}, {:user=>"Bob Blue", :email=>"b@b.com"}]
extract_emails "Abe Allen <a@a.com>, Bob Blue <b@b.com>, c@c.com"
# => [{:user=>"Abe Allen", :email=>"a@a.com"}, {:user=>"Bob Blue", :email=>"b@b.com"}, {:user=>nil, :email=>"c@c.com"}]
I don't know of a library, but if you are trying to get a list of the emails you could do the following yourself. 我不知道图书馆,但如果您想获得电子邮件列表,您可以自己完成以下操作。 (Long winded on purpose)
(故意啰嗦)
@a = "Abe Allen <a@a.com>, Bob Blue <b@b.com>, c@c.com"
b = @a.split(',') #=> ["Abe Allen <a@a.com>", " Bob Blue <b@b.com>", " c@c.com"]
c = b.collect{|x| x[/<(.*?)>|^([^<>]*)$/]} #=> ["<a@a.com>", "<b@b.com>", " c@c.com"]
d = c.gsub(/[<>]/,'') #=> ["a@a.com", "b@b.com", " c@c.com"]
If you want to match their names and email addresses, you will need something else. 如果您想匹配他们的姓名和电子邮件地址,您将需要其他内容。
Also, this won't work if there are '<' or '>' in the email address, but that's pretty uncommon. 此外,如果电子邮件地址中有“<”或“>”,这将无效,但这种情况非常罕见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.