本身并不是这个问题的真正答案,但如果有人需要它,我编写了一个 C# 函数来使用这种方法验证电子邮件地址。
FixEmailAddress("walter@xyz.com")
返回"walter@xyz.com"
FixEmailAddress("wa@lter@xyz.com,tom@xyz.com,asdfdsf,vsav-sdfsd@xyz.xyz")
返回"tom@xyz.com,vsav-sdfsd@xyz.xyz"
我以这种方式处理电子邮件地址列表,因为逗号分隔的电子邮件列表是 MailAddressCollection.Add() 的有效参数
/// <summary>
/// Given a single email address, return the email address if it is valid, or empty string if invalid.
/// or given a comma delimited list of email addresses, return the a comma list of valid email addresses from the original list.
/// </summary>
/// <param name="emailAddess"></param>
/// <returns>Validated email address(es)</returns>
public static string FixEmailAddress(string emailAddress)
{
string result = "";
emailAddress = emailAddress.Replace(";",",");
if (emailAddress.Contains(","))
{
List<string> results = new List<string>();
string[] emailAddresses = emailAddress.Split(new char[] { ',' });
foreach (string e in emailAddresses)
{
string temp = FixEmailAddress(e);
if (temp != "")
{
results.Add(temp);
}
}
result = string.Join(",", results);
}
else
{
try
{
System.Net.Mail.MailAddress email = new System.Net.Mail.MailAddress(emailAddress);
result = email.Address;
}
catch (Exception)
{
result = "";
}
}
return result;
}