C#에서 이메일 주소 유효성 검사하기
C#에서 이메일 주소의 유효성을 검사하는 방법은 여러 가지가 있으며, 대표적으로 System.Net.Mail과 System.Text.RegularExpressions 두 가지 접근 방식을 활용할 수 있습니다.
System.Net.Mail − 이 네임스페이스는 전자 메일을 SMTP(Simple Mail Transfer Protocol) 서버로 전송하여 배달하는 데 사용되는 클래스들을 포함하고 있습니다.
System.Text.RegularExpressions − 이 네임스페이스는 변경 불가능한(immutable) 정규식을 나타내며, 문자열 패턴 매칭에 활용됩니다.
정규식을 사용할 경우 아래 표현식을 활용할 수 있습니다.
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([azA-Z]{2,4}|[0-9]{1,3})(\]?)$"또한 System.Net.Mail 네임스페이스의 MailAddress 클래스를 사용하면 간편하게 이메일 주소의 유효성을 검사할 수 있습니다.
예제 1: MailAddress 클래스 활용
using System;
using System.Net.Mail;
namespace DemoApplication{
class Program{
public static void Main(){
try{
string email = "hello@xyzcom";
Console.WriteLine($"The email is {email}");
var mail = new MailAddress(email);
bool isValidEmail = mail.Host.Contains(".");
if(!isValidEmail){
Console.WriteLine($"The email is invalid");
} else {
Console.WriteLine($"The email is valid");
}
Console.ReadLine();
}
catch(Exception){
Console.WriteLine($"The email is invalid");
Console.ReadLine();
}
}
}
}출력 결과
위 코드의 실행 결과는 다음과 같습니다.
The email is hello@xyzcom The email is invalid
위 예제에서 hello@xyzcom은 호스트 부분에 마침표(.)가 포함되어 있지 않기 때문에 유효하지 않은 이메일로 판별됩니다. 만약 형식 자체가 잘못되어 MailAddress 객체 생성 시 예외가 발생하면 catch 블록에서 처리하여 역시 유효하지 않다고 출력합니다.
예제 2: 정규식(Regex) 활용
정규식을 사용해서도 이메일 주소의 유효성을 검사할 수 있습니다. 정규식 방식은 원하는 패턴 규칙을 직접 정의할 수 있어 더 세밀한 검증이 가능합니다.
예제
using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
public class Program{
public static void Main(){
string email = "hello@xyz.com";
Regex regex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-
9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Singleline);
Console.WriteLine($"The email is {email}");
bool isValidEmail = regex.IsMatch(email);
if (!isValidEmail){
Console.WriteLine($"The email is invalid");
} else {
Console.WriteLine($"The email is valid");
}
Console.ReadLine();
}
}
}출력 결과
위 코드의 실행 결과는 다음과 같습니다.
The email is hello@xyz.com The email is valid
이처럼 C#에서는 MailAddress 클래스를 이용한 간단한 검증 방식과, Regex를 이용한 정교한 패턴 검증 방식 중 상황에 맞게 선택하여 이메일 주소의 유효성을 검사할 수 있습니다.