Skip to content

Instantly share code, notes, and snippets.

@asfaltboy
Created October 9, 2016 17:48
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save asfaltboy/79a02a2b9871501af5f00c95daaeb6e7 to your computer and use it in GitHub Desktop.
Save asfaltboy/79a02a2b9871501af5f00c95daaeb6e7 to your computer and use it in GitHub Desktop.
EmailType: a custom argparse type to validate email addresses
"""
A custom type for argparse, to facilitate validation of email addresses.
Inspired by this SO question: http://stackoverflow.com/questions/14665234/argparse-choices-structure-of-allowed-values
and this gist: https://gist.github.com/gurunars/449edbccd0de1449b71524c89d61e1c5
"""
import re
import argparse
class EmailType(object):
"""
Supports checking email agains different patterns. The current available patterns is:
RFC5322 (http://www.ietf.org/rfc/rfc5322.txt)
"""
patterns = {
'RFC5322': re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"),
}
def __init__(self, pattern):
if pattern not in self.patterns:
raise KeyError('{} is not a supported email pattern, choose from:'
' {}'.format(pattern, ','.join(self.patterns)))
self._rules = pattern
self._pattern = self.patterns[pattern]
def __call__(self, value):
if not self._pattern.match(value):
raise argparse.ArgumentTypeError(
"'{}' is not a valid email - does not match {} rules".format(value, self._rules))
return value
def main():
parser = argparse.ArgumentParser()
parser.add_argument('email', type=EmailType('RFC5322'))
args = parser.parse_args()
print(args.email)
if __name__ == '__main__':
main()
@mrcoles
Copy link

mrcoles commented Sep 2, 2022

Thanks for creating this! Here’s a simpler variation for anyone wanting something more succinct:

import re
import argparse

RE_EMAIL = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")


def email_type(value):
    if not RE_EMAIL.match(value):
        raise argparse.ArgumentTypeError(f"'{value}' is not a valid email")
    return value

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('email', type=email_type)
    args = parser.parse_args()

    print(args.email)

if __name__ == '__main__':
    main()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment