using DnsClient;
using Masuit.Tools.Config;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
namespace Masuit.Tools.Core.Validator;
///
/// 邮箱校验
///
public class IsEmailAttribute : ValidationAttribute
{
private readonly bool _valid;
private readonly string _customMessage;
///
/// 域白名单
///
private string[] WhiteList { get; set; }
///
/// 域黑名单
///
private string[] BlockList { get; set; }
///
/// 是否允许为空
///
public bool AllowEmpty { get; set; }
///
/// 可在配置文件AppSetting节中添加EmailDomainWhiteList配置邮箱域名白名单,EmailDomainBlockList配置邮箱域名黑名单,英文分号(;)或感叹号(!)或逗号(,)分隔,每个单独的元素支持正则表达式
///
/// 是否检查邮箱DNS记录的有效性
/// 自定义错误消息
public IsEmailAttribute(bool validDns = true, string customMessage = null)
{
_valid = validDns;
_customMessage = customMessage;
}
///
/// 邮箱校验
///
///
///
public override bool IsValid(object value)
{
WhiteList = ConfigHelper.Get("EmailDomainWhiteList") ?? [];
BlockList = ConfigHelper.Get("EmailDomainBlockList") ?? [];
if (AllowEmpty)
{
switch (value)
{
case null:
case string s when string.IsNullOrEmpty(s):
return true;
}
}
if (value == null)
{
ErrorMessage = _customMessage ?? "邮箱不能为空!";
return false;
}
var email = (string)value;
if (email.Length < 7)
{
ErrorMessage = _customMessage ?? "您输入的邮箱格式不正确!";
return false;
}
if (email.Length > 256)
{
ErrorMessage = _customMessage ?? "您输入的邮箱无效,请使用真实有效的邮箱地址!";
return false;
}
if (WhiteList.Any(item => Regex.IsMatch(email, item)))
{
return true;
}
if (BlockList.Any(item => Regex.IsMatch(email, item)))
{
ErrorMessage = _customMessage ?? "您输入的邮箱无效,请使用真实有效的邮箱地址!";
return false;
}
var isMatch = email.MatchEmail().isMatch;
if (isMatch && _valid)
{
var nslookup = new LookupClient();
var records = nslookup.Query(email.Split('@')[1], QueryType.MX).Answers.MxRecords().ToList();
if (records.Exists(r => BlockList.Any(item => Regex.IsMatch(r.Exchange.Value, item))))
{
ErrorMessage = _customMessage ?? "您输入的邮箱无效,请使用真实有效的邮箱地址!";
return false;
}
var task = records.SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
{
if (t.IsCanceled || t.IsFaulted)
{
return [IPAddress.Loopback];
}
return t.Result;
}));
isMatch = task.Result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
}
if (isMatch)
{
return true;
}
ErrorMessage = _customMessage ?? "您输入的邮箱格式不正确!";
return false;
}
}