Email Syntax Check in Python

Sometimes you may want to check that an email address is not syntactically invalid, i.e. it looks like a recognisable email address. I use this approach in my zetact contact form processor.

Of course, it does not mean the address actually leads anywhere, but at least you know are dealing with an email address that could exist.

This is the code I have been using, albeit I have changed it from a class method to a simple function to make this post simpler.

"""Email check using regex."""
    def invalidreg(emailkey):
        """Email validation, checks for syntactically invalid email
        courtesy of Mark Nenadov.
        See
        http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65215"""
        import re
        emailregex =
        "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3\
    })(\\]?)$"
        if len(emailkey) > 7:
            if re.match(emailregex, emailkey) != None:
                return False
            return True
        else:
            return True

I decided it would be more Pythonic to try to do this using the built-in string methods, rather than importing the re module and using a monster regular expression. Here was my first attempt.

"""Email checks using string methods - simple version."""
    def invalidemail(emailaddress):
        """Checks for a syntactically invalid email address."""
        try:
            emailitems = emailaddress.rsplit('@', 1)
            emailitems.extend(emailitems[1].rsplit('.', 1))
        except IndexError:
            return True

        if [x for x in emailitems if not x.replace(".","").isalnum()] \
                and emailaddress >= 7:
            return True
        else:
            return False

After a bit of testing and playing with this, a friend pointed me towards the relevant RFC on restrictions of email addresses. While the standard allows the use of many different special characters, in practice email addresses have to be much stricter if you actually want people in the real world to be able to send email to you.

For example, if we allow the email address []@commandline.org.uk, will whatever receives the output of this function be able to use it? As pointed out by Jan Goyvaerts, most software won't actually be able to handle obscure special characters.

We also don't want to water down the syntax check and allow junk for the sake of theoretical but non-existent addresses.

My compromise is to allow these special symbols -_.%+. in the local-part of the email address, and -_. in the domain name. I also do sanity checking on the top-level domain, it needs to be either a generic name or two characters long (country codes are all two letters).

So below is my current version, I added lots of comments and white space to make it easy to read.

"""Ditch nonsense email addresses."""

    GENERIC_DOMAINS = "aero", "asia", "biz", "cat", "com", "coop", \
        "edu", "gov", "info", "int", "jobs", "mil", "mobi", "museum", \
        "name", "net", "org", "pro", "tel", "travel"

    def invalid(emailaddress, domains = GENERIC_DOMAINS):
        """Checks for a syntactically invalid email address."""

        # Email address must be 7 characters in total.
        if len(emailaddress) < 7:
            return True # Address too short.

        # Split up email address into parts.
        try:
            localpart, domainname = emailaddress.rsplit('@', 1)
            host, toplevel = domainname.rsplit('.', 1)
        except ValueError:
            return True # Address does not have enough parts.

        # Check for Country code or Generic Domain.
        if len(toplevel) != 2 and toplevel not in domains:
            return True # Not a domain name.

        for i in '-_.%+.':
            localpart = localpart.replace(i, "")
        for i in '-_.':
            host = host.replace(i, "")

        if localpart.isalnum() and host.isalnum():
            return False # Email address is fine.
        else:
            return True # Email address has funny characters.

    # Start the ball rolling.
    if __name__ == "__main__":
        print invalid("warrior@example.com")

Discuss this post - Leave a comment

16 thoughts on “Email Syntax Check in Python

  1. <p>There's a better, if utterly horrible to read way of doing this using
    regex's.</p>
    <p><a class="reference external" href="http://emailverification.pastecode.com/?show=f76a41a8b">http://emailverification.pastecode.com/?show=f76a41a8b</a></p>
    <p>This way isn't too bad, it allows <a class="reference external" href="mailto:blah+thesethingys&#64;example.com">blah+thesethingys&#64;example.com</a> which a lot
    of websites invalidate (Which is incredibly annoying)..
    One thing I find a little weird - a return of False means the email is valid?
    I would have though if valid(mail): print &quot;Valid email&quot; would be a more
    sensible way of doing things?
    That way: if not valid(email): print &quot;Wrong&quot; # would work</p>

  2. <p>I like the idea in your last example to check that the Domain is valid -
    problem is...what about users with subdomain email addresses
    (<a class="reference external" href="mailto:ted&#64;mail.example.com">ted&#64;mail.example.com</a>) or users with country email domains
    (<a class="reference external" href="mailto:ted&#64;example.co.uk">ted&#64;example.co.uk</a>)</p>

  3. <p>&#64;dbr,</p>
    <p>Checking for syntactically invalid email addresses is what the function does,
    so:</p>
    <div class="highlight"><pre><span class="k">if</span> <span class="n">invalid</span><span class="p">(</span><span class="n">emailaddress</span><span class="p">):</span>
    <span class="c">#do something</span>
    </pre></div>
    <p>Otherwise the program can just carry on, no else clause required. Maybe my
    programming style is just different, you can easily change it to be the other
    way if you want.</p>
    <p>Ted, If you read the code more carefully or try it out, you will see that both of
    your examples will pass the test.</p>
    <p>subdomains are not a problem because I allow dots in the hostname: for i in '-_.':</p>
    <p>Country code domains are catered for by if len(toplevel) != 2</p>

  4. <p>&#64;dbr</p>
    <p>On regular expressions, the aim of this post is to use Python built-in string
    methods instead of regular expressions. Your example,
    <a class="reference external" href="mailto:blah+thesethingys&#64;example.com">blah+thesethingys&#64;example.com</a> will be considered valid by my function as I
    allow the plus sign:
    for i in '-_.%+.'</p>

  5. <p>Here is dbr's regular expression (the pastebin is only temporary).</p>
    <div class="highlight"><pre><span class="k">import</span> <span class="nn">re</span>

    <span class="n">monster</span> <span class="o">=</span> <span class="s">&quot;(?:[a-z0-9!#$%&amp;&#39;*+/=?^_{|}~-]+(?:.[a-z0-9!#$%&quot;</span> <span class="o">+</span> \
    <span class="s">&quot;&amp;&#39;*+/=?^_{|}~-]+)*|</span><span class="se">\&quot;</span><span class="s">(?:&quot;</span> <span class="o">+</span> \
    <span class="s">&quot;[</span><span class="se">\x01</span><span class="s">-</span><span class="se">\x08\x0b\x0c\x0e</span><span class="s">-</span><span class="se">\x1f\x21\x23</span><span class="s">-</span><span class="se">\x5b\x5d</span><span class="s">-</span><span class="se">\x7f</span><span class="s">]&quot;</span> <span class="o">+</span> \
    <span class="s">&quot;|</span><span class="se">\\</span><span class="s">[</span><span class="se">\x01</span><span class="s">-</span><span class="se">\x09\x0b\x0c\x0e</span><span class="s">-</span><span class="se">\x7f</span><span class="s">])*</span><span class="se">\&quot;</span><span class="s">)@(?<img src="/static/forum/img/smilies/sad.png">?:[a-z0-9]&quot;</span> <span class="o">+</span> \
    <span class="s">&quot;(?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?&quot;</span> <span class="o">+</span> \
    <span class="s">&quot;|\[(?<img src="/static/forum/img/smilies/sad.png">?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)&quot;</span> <span class="o">+</span> \
    <span class="s">&quot;{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?&quot;</span> <span class="o">+</span> \
    <span class="s">&quot;|[a-z0-9-]*[a-z0-9]<img src="/static/forum/img/smilies/sad.png">?:&quot;</span> <span class="o">+</span> \
    <span class="s">&quot;[</span><span class="se">\x01</span><span class="s">-</span><span class="se">\x08\x0b\x0c\x0e</span><span class="s">-</span><span class="se">\x1f\x21</span><span class="s">-</span><span class="se">\x5a\x53</span><span class="s">-</span><span class="se">\x7f</span><span class="s">]&quot;</span> <span class="o">+</span> \
    <span class="s">&quot;|</span><span class="se">\\</span><span class="s">[</span><span class="se">\x01</span><span class="s">-</span><span class="se">\x09\x0b\x0c\x0e</span><span class="s">-</span><span class="se">\x7f</span><span class="s">])+)\])&quot;</span>

    <span class="n">evil</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="n">monster</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">evil</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">&quot;<a href="mailto:test+label@google.museum.au">test+label@google.museum.au</a>&quot;</span><span class="p">):</span>
    <span class="k">print</span> <span class="s">&quot;yay!&quot;</span>
    </pre></div>

  6. <p>Just as an FYI, I get an 'XML Parsing Error: not well-formed' message in my
    newsreader (Liferea) for this entry. Line number 94, Column 98.</p>
    <p>This is the first (mostly/enough) valid email checker I've seen that doesn't
    use a monster regex. I definitely like it.</p>

  7. <p>&#64;Zeth</p>
    <p>ARGH - I feel like such a n00b. You, my friend, are absolutely correct.
    Thanks for clearing that up for me.</p>

  8. <p>Zeth,</p>
    <p>Thank you for this post, very helpful.
    I used it as a basis for my own email validation function that i wish to share with you, in a selfish attempt to feel better about using your code.</p>
    <p>I delegated the domain verification to dns, It sounds like a good idea, but im not aware at the moments of any drawbacks. please let me know what you think. Here's my code:</p>
    <div class="highlight"><pre><span class="k">import</span> <span class="nn">dns.resolver</span>

    <span class="k">def</span> <span class="nf">valid</span><span class="p">(</span> <span class="n">email_address</span> <span class="p">):</span>
    <span class="c"># check email parts</span>
    <span class="k">try</span><span class="p">:</span>
    <span class="n">username</span><span class="p">,</span> <span class="n">domain</span> <span class="o">=</span> <span class="n">email_address</span><span class="o">.</span><span class="n">rsplit</span><span class="p">(</span><span class="s">&#39;@&#39;</span><span class="p">,</span> <span class="mf">1</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
    <span class="k">return</span> <span class="bp">False</span>
    <span class="c"># check username: allow alphanumeric characters and the dot</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">username</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span> <span class="s">&#39;.&#39;</span><span class="p">,</span> <span class="s">&#39;&#39;</span> <span class="p">)</span><span class="o">.</span><span class="n">isalnum</span><span class="p">():</span>
    <span class="k">return</span> <span class="bp">False</span>
    <span class="c"># check domain</span>
    <span class="k">try</span><span class="p">:</span>
    <span class="n">dns_response</span> <span class="o">=</span> <span class="n">dns</span><span class="o">.</span><span class="n">resolver</span><span class="o">.</span><span class="n">query</span><span class="p">(</span> <span class="n">domain</span><span class="p">,</span> <span class="s">&#39;MX&#39;</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">dns</span><span class="o">.</span><span class="n">resolver</span><span class="o">.</span><span class="n">NoAnswer</span><span class="p">:</span>
    <span class="c"># this host doesn&#39;t have MX records</span>
    <span class="k">return</span> <span class="bp">False</span>
    <span class="k">except</span> <span class="n">dns</span><span class="o">.</span><span class="n">resolver</span><span class="o">.</span><span class="n">NXDOMAIN</span><span class="p">:</span>
    <span class="c"># no such hostname</span>
    <span class="k">return</span> <span class="bp">False</span>
    <span class="k">return</span> <span class="bp">True</span>
    </pre></div>
    <p>by the way, on line 11 of your second code snippet, shouldn't it be &quot;len(emailaddress) &gt;= 7&quot; as opposed to emailaddress &gt;= 7.</p>
    <p>Also, you can call the function like this:</p>
    <div class="highlight"><pre><span class="k">if</span> <span class="ow">not</span> <span class="n">valid</span><span class="p">(</span> <span class="n">email_address</span> <span class="p">):</span>
    <span class="c"># do this</span>
    </pre></div>
    <p>without requiring and else part as well. however its all a matter of taste. both ways seem valid to me.</p>
    <p>Thanks again!</p>

  9. <p>Thanks Omar, that is a really good snippet, thanks for taking the time to share it with us.</p>

  10. <p>Personally I don't bother with email syntax checking - it seems pointless to me. The majority of typos are going to be of the form <a class="reference external" href="mailto:tpyo&#64;examlpe.com">tpyo&#64;examlpe.com</a>, which the syntax check wouldn't catch.</p>
    <p>Omar - I like your script, checking DNS is a good idea, but there is one thing you should know. It looks like you're checking for the MX record, which is great, except that the RFC specifies if no MX record is found but there is a CNAME you should use that instead.</p>
    <p>All this means that email is actually a complicated business. I think the only way to be sure of an email address, if it's really important, is to send someone a link to that address with a confirmation token and have them click on it.</p>
    <p>And the reason I'm posting this nearly three months after the original post is because I just noticed the comments <img src="/static/forum/img/smilies/smile.png"></p>

  11. <p>I'm sure I found a work around for this when I used zetact around the time of this post.. , but this regex excludes the email address <a class="reference external" href="mailto:andy&#64;lnmf.info">andy&#64;lnmf.info</a>.</p>
    <p>Any ideas how to change it to allow that form of address?</p>

  12. <p>hey all,
    i just wanted to check the other stuf if nay1 can help me
    what i want is i have to convert the line starting with my function name to some other format , i have done with that much part but what i want ahead is the line wont be everytime starting as a first character so it may have like my function name if having some other check also in itself wherin say if chaeck is to be done to be verified for the same line if it is acceptable then convert the line else not</p>

  13. <p>The regex in comment #5 is generally pretty good, but it incorrectly matches strings such as 'john&#64;doe&#64;johndoe.com'. As per Wikipedia, an email address can have only one '&#64;' sign.</p>

  14. <p>The regexp in #5 also allows:</p>
    <blockquote>
    <a class="reference external" href="mailto:me+suffix+another+another&#64;myhost.com">me+suffix+another+another&#64;myhost.com</a></blockquote>
    <p>and fails:</p>
    <blockquote>
    <a class="reference external" href="mailto:localuser&#64;localmachine">localuser&#64;localmachine</a></blockquote>

How about Global Thermonuclear War? Wouldn't you prefer a good game of chess? Powered by zpress