Mask email address C# .Net 8

This is a C# extension method that will mask your email address following this pattern:

  • If it’s not an email, the entire string will be masked (“this string” => “***********”)
  • If the first part of the email is shorter than 4 characters, the entire email will be masked (me@somewhere.com => *@*.*)
  • All other emails are masked leaving only the first and last characters of the name and domain (somebody@somewhere.com => s******y@s*******e.com)

The Extension Method:


using System;
using System.Text.RegularExpressions;
namespace YourNamespace
{
  public static class EmailMasker
  {
    private static string _PATTERN = @"(?<=[\w]{1})[\w-\._\+%\\]*(?=[\w]{1}@)|(?<=@[\w]{1})[\w-_\+%]*(?=\.)";
 
    public static string MaskEmail(this string s)
    {
      if (!s.Contains("@"))
        return new String('*', s.Length);
      if (s.Split('@')[0].Length < 4) 
        return @"*@*.*"; 
      return Regex.Replace(s, _PATTERN, m => new string('*', m.Length));
    }
  }
}

 

Usage:


using YourNamespace;
public void TestMethod()
{
  string email = "someperson@somedomain.com";
  string maskedEmail = email.MaskEmail();
  //// result: s********n@s********n.com
}

Summary: