Last Updated: May 07, 2018
·
5.751K
· theskumar

Mask email for public viewing as user identifier.

I'm sharing small utility to convert an email to publically viewable user id. The use case is a system where user's don't have username but we still need to identify the person via some automatically generated user id.

e.g. saurabh@example.com would become saur…@example.com

This type email masking can also be found on google-groups user interface, where if you click on a masked email, it will do a captcha verification before displaying the full email.

import math


def mask_email(email):
    """
    Converts an email to publically viewable as user identifier after hiding parts
    email.

    Usages:
    >>> mask_email("a@a.com")
    'a…@a.com'
    >>> mask_email("aa@a.com")
    'a…@a.com'
    >>> mask_email("abc@a.com")
    'ab…@a.com'
    >>> mask_email("abcd@a.com")
    'ab…@a.com'
    >>> mask_email("this-is-a-verylongemail-that-should-be-trimmed@gmail.com")
    'this-is-a-…@gmail.com'
    >>> mask_email("invalidemail")
    'invalidemail'
    """
    if '@' not in email:
        return email
    first, domain = email.split("@", 1)
    hide_after = min(math.ceil(len(first) / 2), 10)
    return '{}…@{}'.format(first[:hide_after], domain)