Detect Disposable Email Addresses
A common problem with signing up users for a newsletter or a trial is to try and prevent a user registering with a disposable email address. The best list that I can find of disposable email addresses is here :
I have created a script that uses the HttpClient to download a list of disposable addresses from GitHub. The list can then be stored in a database table and used to validate a users email domain when registering for a newsletter or account.
Disposable Email Service
There are two classes defined :
- DisposableEmailResponse - This contains the service response (success, error message, list of domains)
- DisposableEmailService - This gets the list of Disposable Email Domains
using System.Net.Http
using System.Net.Mail
using System.Threading.Tasks
using Newtonsoft.Json
public class DisposableEmailResponse
{
public bool IsSuccess { get; set; }
public string ErrorMessage { get; set; }
public IEnumerable<string> DisposableEmailDomains { get; set; } = new List<string>();
}
public class DisposableEmailService
{
public async Task<DisposableEmailResponse> Get(CancellationToken cancellationToken)
{
const string GithubBlacklist
= "https://raw.githubusercontent.com/ivolo/disposable-email-domains/master/index.json";
var result = new DisposableEmailResponse();
using (var client = new HttpClient())
{
try
{
var response = await client.GetAsync(GithubBlacklist, cancellationToken);
response.EnsureSuccessStatusCode();
var contents = await response.Content.ReadAsStringAsync();
result.IsSuccess = true;
result.DisposableEmailDomains = JsonConvert.DeserializeObject<List<string>>(contents);
}
catch (TaskCanceledException)
{
result.ErrorMessage = $"{nameof(Get)} task has been cancelled";
}
catch (Exception ex)
{
result.ErrorMessage = $"{nameof(Get)} has errored : {ex.Message}";
}
}
return result;
}
}
Usage
I use LINQPad as my default scratchpad for creating scripts and services. The script above references the following nuget packages
- Newtonsoft.Json
The code below shows how to use the DisposableEmailService
async Task Main()
{
var disposableEmails = await GetDisposableEmailAddresses();
var testEmail = "chethostat@matra.site";
var mailAddress = new MailAddress(testEmail);
var domainPart = mailAddress.Host.ToLower();
if (disposableEmails.Contains(domainPart))
Console.Write($"The email is invalid {testEmail}, Disposable email addresses are disallowed from registering");
}
public async Task<List<string>> GetDisposableEmailAddresses()
{
var token = new CancellationToken();
var disposableEmailService = new DisposableEmailService();
var disposableEmails = await disposableEmailService.Get(token);
return disposableEmails.DisposableEmailDomains.ToList();
}