如何使用 C# 验证邮件地址

本文介绍了一个使用C#实现的方法,该方法通过解析电子邮件地址并利用nslookup命令来获取指定邮件服务器的MX记录,从而确定邮件交换器地址。此外,还包括了一个用于验证电子邮件地址格式的正则表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System.Text.RegularExpressions;
using System.Diagnostics;
using System.IO;
//检查邮件服务器,如果mail exchanger不为null,返回mail server地址
        public string getMailServer(string strEmail)
        {
            if (!IsEmail(strEmail))
            {
                return null;
            }
            string strDomain = strEmail.Trim().ToLower().Split('@')[1];
            ProcessStartInfo PSinfo = new ProcessStartInfo();
            PSinfo.UseShellExecute = false;
            PSinfo.RedirectStandardInput = true;
            PSinfo.RedirectStandardOutput = true;
            PSinfo.FileName = "nslookup";
            PSinfo.CreateNoWindow = true;
            PSinfo.Arguments = "-type=mx " + strDomain;
            Process proc = Process.Start(PSinfo);
            StreamReader Sreader = proc.StandardOutput;
            Regex rgx = new Regex("mail exchanger = (?<mailServer>[^//s]+)");
            string strResponse = "";
            while ((strResponse = Sreader.ReadLine()) != null)
            {
                Match aMatch = rgx.Match(strResponse);
                if (rgx.Match(strResponse).Success)
                {
                    string Gvalue = aMatch.Groups["mailServer"].Value;
                    return Gvalue;
                }
            }
            return null;
        }
        //正则表达式验证Email地址格式
        public bool IsEmail(string str_Email)
        {
            return Regex.IsMatch(str_Email, @"^([/w-/.]+)+[a-zA-Z0-9]+@((/[[0-9]{1,3}/.[0-9]{1,3}/.[0-9]{1,3}/.)|(([/w-]+/.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(/]?)$");
        }


 http://blog.youkuaiyun.com/kimiqiu/archive/2009/07/03/4319649.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值