[英]Best way to validate email address format in C#
嗨,我正在開發批量 email 發送功能。 下面是驗證 email 並將它們發送給每個收件人的循環:
foreach (var userID in recipientUserIds)
{
var userInfo = //getting from database using userID.
try
{
to = new MailAddress(userInfo.Email1, userInfo.FirstName + " " + userInfo.LastName);
}
catch (System.FormatException fe)
{
continue;
}
using (MailMessage message = new MailMessage(from, to))
{
//populate message and send email.
}
}
由於 recipientUserIds 總是超過 2000,因此在這種情況下,使用 try-catch 對於每個用戶來說似乎非常昂貴,只是為了驗證 email 地址格式。 我想知道使用正則表達式,但不確定這是否有助於提高性能。
所以我的問題是是否有更好或性能優化的方法來進行相同的驗證。
驗證 email 地址是一項復雜的任務,編寫代碼來預先完成所有驗證將非常棘手。 如果您查看MailAddress
class 文檔的Remarks
部分,您會發現有很多字符串被認為是有效的 email 地址(包括注釋、括號內的域名和嵌入的引號)。
由於源代碼可用,請在此處查看ParseAddress
方法,您將了解自己驗證 email 地址所需編寫的代碼。 遺憾的是,沒有可以用來避免拋出異常的公共TryParse
方法。
所以最好先做一些簡單的驗證——確保它包含 email 地址的最低要求(字面意思是user@domain
,其中domain
不必包含'.'
字符),然后讓異常處理負責 rest:
foreach (var userID in recipientUserIds)
{
var userInfo = GetUserInfo(userID);
// Basic validation on length
var email = userInfo?.Email1?.Trim();
if (string.IsNullOrEmpty(email) || email.Length < 3) continue;
// Basic validation on '@' character position
var atIndex = email.IndexOf('@');
if (atIndex < 1 || atIndex == email.Length - 1) continue;
// Let try/catch handle the rest, because email addresses are complicated
MailAddress to;
try
{
to = new MailAddress(email, $"{userInfo.FirstName} {userInfo.LastName}");
}
catch (FormatException)
{
continue;
}
using (MailMessage message = new MailMessage(from, to))
{
// populate message and send email here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.