1
0

E-Mail Validierung hinzugefügt

This commit is contained in:
2021-11-22 22:13:29 +01:00
parent 0736d54c87
commit e31aa18546
4 changed files with 106 additions and 1 deletions

View File

@@ -36,6 +36,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="DnsClient" Version="1.5.0" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.1" />
<PackageReference Include="Unclassified.DeepConvert" Version="1.3.0" />
<PackageReference Include="Unclassified.NetRevisionTask" Version="0.4.1">

View File

@@ -1,8 +1,11 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using DnsClient;
namespace System
{
@@ -137,5 +140,50 @@ namespace System
return decimal.Parse(decString, culture);
}
/// <summary>
/// Checks whether the given <see cref="string"/> is a valid <see cref="MailAddress"/>.
/// </summary>
/// <remarks>
/// You can enhance the check by requesting the MX record of the domain.
/// </remarks>
/// <param name="email">The email address as string to validate.</param>
/// <param name="checkRecordExists">A value indicating whether to resolve a MX record.</param>
/// <returns><c>true</c> when the email address is valid, other wise <c>false</c>.</returns>
public static bool IsValidEmailAddress(this string email, bool checkRecordExists = false)
=> email.IsValidEmailAddress(checkRecordExists ? new LookupClient() : null);
/// <summary>
/// Checks whether the given <see cref="string"/> is a valid <see cref="MailAddress"/>.
/// </summary>
/// <remarks>
/// The check is enhanced by a request for MX records on the defined <paramref name="nameservers"/>.
/// </remarks>
/// <param name="email">The email address as string to validate.</param>
/// <param name="nameservers">A list of <see cref="IPEndPoint"/>s of nameservers.</param>
/// <returns><c>true</c> when the email address is valid, other wise <c>false</c>.</returns>
public static bool IsValidEmailAddress(this string email, IEnumerable<IPEndPoint> nameservers)
=> email.IsValidEmailAddress(new LookupClient(nameservers.ToArray()));
private static bool IsValidEmailAddress(this string email, LookupClient lookupClient)
{
try
{
var mailAddress = new MailAddress(email);
bool isValid = mailAddress.Address == email;
if (isValid && lookupClient != null)
{
var result = lookupClient.Query(mailAddress.Host, QueryType.MX);
isValid &= result.Answers.MxRecords().Any();
}
return isValid;
}
catch
{
return false;
}
}
}
}