282

Is there a good way to check a form input using regex to make sure it is a proper style email address? Been searching since last night and everybody that has answered peoples questions regarding this topic also seems to have problems with it if it is a subdomained email address.

0

18 Answers 18

360

There is no point. Even if you can verify that the email address is syntactically valid, you'll still need to check that it was not mistyped, and that it actually goes to the person you think it does. The only way to do that is to send them an email and have them click a link to verify.

Therefore, a most basic check (e.g. that they didn't accidentally entered their street address) is usually enough. Something like: it has exactly one @ sign, and at least one . in the part after the @:

[^@]+@[^@]+\.[^@]+

You'd probably also want to disallow whitespace -- there are probably valid email addresses with whitespace in them, but I've never seen one, so the odds of this being a user error are on your side.

If you want the full check, have a look at this question.


Update: Here's how you could use any such regex:

import re

if not re.match(r"... regex here ...", email):
  # whatever

Python ≥3.4 has re.fullmatch which is preferable to re.match.

Note the r in front of the string; this way, you won't need to escape things twice.

If you have a large number of regexes to check, it might be faster to compile the regex first:

import re

EMAIL_REGEX = re.compile(r"... regex here ...")

if not EMAIL_REGEX.match(email):
  # whatever

Another option is to use the validate_email package, which actually contacts the SMTP server to verify that the address exists. This still doesn't guarantee that it belongs to the right person, though.

17
  • 1
    So than basically my best bet would be if not re.match("[^@]+@[^@]+\.[^@]+", email): ?
    – Bobby
    Commented Nov 5, 2011 at 19:15
  • 27
    I ended up doing if not re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", email): as this seem the most plausible scenario followed by sending an verification email to the given address.
    – Bobby
    Commented Nov 5, 2011 at 19:44
  • 28
    @Bobby: please loosen that up a lot. I've had to deal with email addresses that that would filter out (e.g. with /, seen in a University's addresses). Another whole class that you're entirely blocking are internationalised domain names. Really, there's no good reason to block valid email addresses. I'll begrudgingly forgive people that don't allow email addresses like 100%." foo b@r"(this is a cool email address!)@(just a tld)com(ok), but I think the check for an @ symbol is really all you should have (a top level domain is valid as the domain part, but it's improbable). Commented Mar 6, 2013 at 6:30
  • 2
    Making it even a little tighter. Seems safe to limit TLD to alphanumeric right now (still haven't seen a TLD that has non-ASCII chars). Using this now: re.compile(r"[^@\s]+@[^@\s]+\.[a-zA-Z0-9]+$")
    – minou
    Commented Aug 29, 2015 at 15:39
  • 3
    @Snowirbis I don't know about the RFC, but I have never seen a practical example of an email address with more than one @. If this does occur, it's more likely to be user error (for example, the user hit Ctrl+V twice by accident) than someone's actual email address.
    – Thomas
    Commented Nov 18, 2020 at 10:20
185

The Python standard library comes with an e-mail parsing function: email.utils.parseaddr().

It returns a two-tuple containing the real name and the actual address parts of the e-mail:

>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')

>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')

>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')

And if the parsing is unsuccessful, it returns a two-tuple of empty strings:

>>> parseaddr('[invalid!email]')
('', '')

An issue with this parser is that it's accepting of anything that is considered as a valid e-mail address for RFC-822 and friends, including many things that are clearly not addressable on the wide Internet:

>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')

>>> parseaddr('invalid-email')
('', 'invalid-email')

So, as @TokenMacGuy put it, the only definitive way of checking an e-mail address is to send an e-mail to the expected address and wait for the user to act on the information inside the message.

However, you might want to check for, at least, the presence of an @-sign on the second tuple element, as @bvukelic suggests:

>>> '@' in parseaddr("invalid-email")[1]
False

If you want to go a step further, you can install the dnspython project and resolve the mail servers for the e-mail domain (the part after the '@'), only trying to send an e-mail if there are actual MX servers:

>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NXDOMAIN

You can catch both NoAnswer and NXDOMAIN by catching dns.exception.DNSException.

And Yes, foo@[email protected] is a syntactically valid address. Only the last @ should be considered for detecting where the domain part starts.

10
  • 5
    @PeterLada: You could just check if there's a @ in the address after using this func, though.
    – user234932
    Commented Jun 26, 2014 at 19:16
  • 1
    parseaddr(u"evil@addr") will break this.
    – Yajo
    Commented Oct 23, 2015 at 15:03
  • 3
    @Yajo, "break this" how?evil@addr is just as valid an e-mail address as [email protected] and is treated as such by parseaddr(). In the end, you'll always need to try sending an e-mail to the provided address for validation.
    – LeoRochael
    Commented Oct 25, 2015 at 18:32
  • 6
    email.utils.parseaddr parses email address but does not validate it email.utils.parseaddr('user@@host') yields ('', 'user@')
    – skoval00
    Commented Feb 15, 2017 at 16:04
  • 1
    I'm not sure why so many upvotes. This is useless since it does pretty much no validations whatsoever, which was the original question. Commented May 8, 2023 at 14:19
95

I haven't seen the answer already here among the mess of custom Regex answers, but...

There exists a python library called py3-validate-email validate_email which has 3 levels of email validation, including asking a valid SMTP server if the email address is valid (without sending an email).

To install

python -m pip install py3-validate-email

Basic usage:

from validate_email import validate_email
is_valid = validate_email(email_address='[email protected]', \
    check_regex=True, check_mx=True, \
    from_address='[email protected]', helo_host='my.host.name', \ 
    smtp_timeout=10, dns_timeout=10, use_blacklist=True)

For those interested in the dirty details, validate_email.py (source) aims to be faithful to RFC 2822.

All we are really doing is comparing the input string to one gigantic regular expression. But building that regexp, and ensuring its correctness, is made much easier by assembling it from the "tokens" defined by the RFC. Each of these tokens is tested in the accompanying unit test file.


you may need the pyDNS module for checking SMTP servers

pip install pyDNS

or from Ubuntu

apt-get install python3-dns
14
  • 1
    sudo apt-get python3-dns seems to work on Ubuntu in place of sudo -H pip3 install pyDNS, just for the record. Commented Sep 1, 2018 at 23:13
  • 7
    This thing returns "True" for just about anything I throw at it. Commented Sep 27, 2018 at 22:47
  • 5
    @philshem, well, the two deeper tests supposed to go out to the mail servers, both return "None" all the time. Don't know why, I will try to rule out that I have some kind of limitation on the network I am on. The simple test, valid syntax, I can throw just about anything to and it will say it's good syntax. I used the pip module in Python 2. Commented Sep 28, 2018 at 13:09
  • 2
    Same result as @Prof.Falken Commented Mar 7, 2019 at 9:06
  • 2
    This is a pretty bad validator. It fails for email@examplecom. See the big list of known issues.
    – Asclepius
    Commented Mar 14, 2019 at 1:21
25

Email addresses are not as simple as they seem! For example, Bob_O'[email protected], is a valid email address.

I've had some luck with the lepl package (http://www.acooke.org/lepl/). It can validate email addresses as indicated in RFC 3696: http://www.faqs.org/rfcs/rfc3696.html

Found some old code:

import lepl.apps.rfc3696
email_validator = lepl.apps.rfc3696.Email()
if not email_validator("[email protected]"):
    print "Invalid email"
4
  • 16
    lepl has now been discontinued.
    – user290043
    Commented Jan 22, 2013 at 13:07
  • 3
    For a simple use case like this, if the current version works the fact it's discontinued is not very relevant. Commented Jul 4, 2013 at 17:32
  • 1
    this method doesn't work when u put email email''[email protected]' It return true for this username too
    – Awesome
    Commented Dec 29, 2017 at 9:09
  • It seems to return False for everything I tried it with, valid or not.
    – Asclepius
    Commented Mar 14, 2019 at 1:16
16

I found an excellent (and tested) way to check for valid email address. I paste my code here:

# here i import the module that implements regular expressions
import re

# here is my function to check for valid email address
def test_email(your_pattern):
  pattern = re.compile(your_pattern)
  # here is an example list of email to check it at the end
  emails = ["[email protected]", "[email protected]", "wha.t.`1an?ug{}[email protected]"]
  for email in emails:
    if not re.match(pattern, email):
        print "You failed to match %s" % (email)
    elif not your_pattern:
        print "Forgot to enter a pattern!"
    else:
        print "Pass"

# my pattern that is passed as argument in my function is here!
pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"   

# here i test my function passing my pattern
test_email(pattern)
5
  • 4
    The only answer here I see here. That checks for characters allowed in RFC 6531 email standards.
    – edlee
    Commented Jun 29, 2017 at 20:51
  • also the plus sign is allowed in the username part of email
    – Mobigital
    Commented Dec 25, 2018 at 19:25
  • 1
    Copy web learnpython.org/en/Regular_Expressions .. only a problem 3rd email is wrong, its invalid cannot special character.
    – KingRider
    Commented Feb 18, 2020 at 11:43
  • 5
    This pattern does not allow the underscore character in email addresses.
    – Alex Lach
    Commented Mar 10, 2020 at 13:44
  • Not correct. [email protected] fits the regex, but [email protected] not. Commented Jul 9 at 11:50
7

I see a lot of complicated answers here. Some of them, fail to knowledge simple, true email address, or have false positives. Below, is the simplest way of testing that the string would be a valid email. It tests against 2 and 3 letter TLD's. Now that you technically can have larger ones, you may wish to increase the 3 to 4, 5 or even 10.

import re
def valid_email(email):
  return bool(re.search(r"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", email))
7
  • 2
    however re.match is better than bool(re.search)
    – Gahan
    Commented Jun 19, 2017 at 5:58
  • 7
    That won't work for UK emails for the record, they end with .co.uk.
    – Peter
    Commented Oct 1, 2017 at 15:54
  • 3
    This won't work for any TLDs that are more than 3 characters
    – kbuilds
    Commented Mar 19, 2018 at 18:29
  • will this validate emails such as [email protected] (because it has 2 dots in the domain name part) ?
    – Mobigital
    Commented Dec 25, 2018 at 19:26
  • 1
    @Peter Now it can handle your use case.
    – Krissh
    Commented Sep 16, 2019 at 7:30
5

This is typically solved using regex. There are many variations of solutions however. Depending on how strict you need to be, and if you have custom requirements for validation, or will accept any valid email address.

See this page for reference: http://www.regular-expressions.info/email.html

5

Email addresses are incredibly complicated. Here's a sample regex that will match every RFC822-valid address: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

You'll notice that it's probably longer than the rest of your program. There are even whole modules for Perl with the purpose of validating email addresses. So you probably won't get anything that's 100% perfect as a regex while also being readable. Here's a sample recursive descent parser: http://cpansearch.perl.org/src/ABIGAIL/RFC-RFC822-Address-2009110702/lib/RFC/RFC822/Address.pm

but you'll need to decide whether you need perfect parsing or simple code.

1
  • According to this documentation ( pythonhosted.org/TurboMail/chapters/detailed.html ) "the original format for email messages was defined in RFC 822 which was superseded by RFC 2822. The newest standard document about the format is currently RFC 5322.". So, using something based on RFC 822 valid? 🤔 Commented Dec 27, 2022 at 4:23
5
import re
def email():
    email = raw_input("enter the mail address::")
     match = re.search(r'[\w.-]+@[\w.-]+.\w+', email)

    if match:
        print "valid email :::", match.group()
    else:
        print "not valid:::"

email()
1
  • 1
    Nice one - I think, though, the "." before the TLD needs to be escaped as "\." Commented Nov 23, 2014 at 21:31
5
from validate_email import validate_email
is_valid = validate_email('[email protected]',verify=True)
print(bool(is_valid))

See validate_email docs.

2
  • 1
    This library is buggy and has been giving a lot of false negatives, causing headache.
    – j4hangir
    Commented Jun 11, 2022 at 19:58
  • this library thinks "example@so" is good email
    – oruchkin
    Commented Jul 7, 2022 at 12:37
3

If you want to take out the mail from a long string or file Then try this.

([^@|\s]+@[^@]+\.[^@|\s]+)

Note, this will work when you have a space before and after your email-address. if you don't have space or have some special chars then you may try modifying it.

Working example:

string="Hello ABCD, here is my mail id [email protected] "
res = re.search("([^@|\s]+@[^@]+\.[^@|\s]+)",string,re.I)
res.group(1)

This will take out [email protected] from this string.

Also, note this may not be the right answer... But I have posted it here to help someone who has specific requirement like me

1
  • 3
    ´re.match("([^@|\s]+@[^@]+\.[^@|\s]+)",email)´ works great
    – palsch
    Commented Dec 13, 2014 at 21:28
1

For check of email use email_validator

from email_validator import validate_email, EmailNotValidError

def check_email(email):
    try:
        v = validate_email(email)  # validate and get info
        email = v["email"]  # replace with normalized form
        print("True")
    except EmailNotValidError as e:
        # email is not valid, exception message is human-readable
        print(str(e))

check_email("test@gmailcom")
1
  • It may be helpful to understand the "practical" intent of this package: "This library validates that a string is of the form [email protected]. This is the sort of validation you would want for an email-based login form on a website."
    – dat
    Commented Feb 13, 2021 at 18:50
0
"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$"
2
  • 18
    Generally, answers, especially to regex-related questions, are much more helpful if they include a fairly detailed explanation of what the code or regex is intended to do, and why that solves the problem without introducing others. This is still more important with something that is as frankly error-prone and fiddly as email address validation; I've seen at least one regex that was a full page long for the purpose, and that was without insignificant whitespace. Commented Feb 11, 2015 at 0:20
  • This appears to be helpful: return re.search("^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", email) != None
    – Vladimir
    Commented May 24, 2020 at 19:20
0

Found this to be a practical implementation:

^[^@\s]+@[^@\s]+\.[^@\s]+$
3
  • 1
    [^@\s]+@[^@\s]+\.[^@\s]+ This is wrong because this will allow spaces in the extension part .c om and spaces are not allowed in emails.
    – WayBehind
    Commented Apr 17, 2020 at 18:25
  • no it won't allow those spaces, that's why it the last part has the \s. example: re.findall(r'[^@\s]+@[^@\s]+\.[^@\s]+', '[email protected] has spaces') = ['[email protected]']
    – juan Isaza
    Commented Apr 20, 2020 at 16:26
  • 1
    EDIT: I was using r.match and re.compile to test, not re.findall so perhaps, we are both correct if used as intended. Unfortunately, you did not provide any details in your answer, and therefore, it was open to misunderstanding. If you edit your answer, I will be able to remove the downvote. Unfortunately, without your answer edit, the system will not let me to change my vote.
    – WayBehind
    Commented Apr 20, 2020 at 19:21
-1

Finding Email-id: finding IP screenshot

import re 
a=open("aa.txt","r")
#c=a.readlines() 
b=a.read()
c=b.split("\n")
print(c)
  for d in c: 
    obj=re.search(r'[\w.]+\@[\w.]+',d)
    if obj:
      print(obj.group())  
#for more calcification click on image above..
1
  • Please edit the code so the indentation is correct, remove the line numbers and press ctrl + K with the code selected to format it.
    – Athena
    Commented Aug 9, 2017 at 12:05
-1

Use this filter mask on email input: emailMask: /[\w.\-@'"!#$%&'*+/=?^_{|}~]/i`

-3

email validation

import re
def validate(email): 
    match=re.search(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9.]*\.*[com|org|edu]{3}$)",email)
    if match:
        return 'Valid email.'
    else:
        return 'Invalid email.'
-4

The only really accurate way of distinguishing real, valid email addresses from invalid ones is to send mail to it. What counts as an email is surprisingly convoluted ("John Doe" <[email protected]>" actually is a valid email address), and you most likely want the email address to actually send mail to it later. After it passes some basic sanity checks (such as in Thomas's answer, has an @ and at least one . after the @), you should probably just send an email verification letter to the address, and wait for the user to follow a link embedded in the message to confirm that the email was valid.

Not the answer you're looking for? Browse other questions tagged or ask your own question.