ここのいくつかの投稿とは対照的に、私は mmutz に同意する必要があります。正規表現でメールを解析することはできません... この記事を参照してください:
https://www.rfc-editor.org/rfc/rfc2822#section-3.4.1
3.4.1. Addr-spec 仕様
addr-spec は、ローカルで解釈された文字列とそれに続くアットマーク文字 (「@」、ASCII 値 64) とそれに続くインターネット ドメインを含む特定のインターネット識別子です。
「ローカルで解釈される」という考えは、受信サーバーだけがそれを解析できると予想されることを意味します。
これを解決しようとすると、「To」行の内容を見つけて分割し、各セグメントを System.Net.Mail.MailAddress で解析しようとします。
static void Main()
{
string input = @"Thread-Topic: test subject
Thread-Index: AcwE4mK6Jj19Hgi0SV6yYKvj2/HJbw==
From: ""Lastname, Firstname"" <firstname_lastname@domain.com>
To: <testto@domain.com>, ""Yes, this is valid""@[emails are hard to parse!], testto1@domain.com, testto2@domain.com
Cc: <testcc@domain.com>, test3@domain.com
X-OriginalArrivalTime: 27 Apr 2011 13:52:46.0235 (UTC) FILETIME=[635226B0:01CC04E2]";
Regex toline = new Regex(@"(?im-:^To\s*:\s*(?<to>.*)$)");
string to = toline.Match(input).Groups["to"].Value;
int from = 0;
int pos = 0;
int found;
string test;
while(from < to.Length)
{
found = (found = to.IndexOf(',', from)) > 0 ? found : to.Length;
from = found + 1;
test = to.Substring(pos, found - pos);
try
{
System.Net.Mail.MailAddress addy = new System.Net.Mail.MailAddress(test.Trim());
Console.WriteLine(addy.Address);
pos = found + 1;
}
catch (FormatException)
{
}
}
}
上記のプログラムからの出力:
testto@domain.com
"Yes, this is valid"@[emails are hard to parse!]
testto1@domain.com
testto2@domain.com