172π
UPDATE 2017: the code below is 7 years old and was since modified, fixed and expanded. For anyone wishing to do this now, the correct code lives around here.
Here is part of django.core.validators you may find interesting π
class EmailValidator(RegexValidator):
def __call__(self, value):
try:
super(EmailValidator, self).__call__(value)
except ValidationError, e:
# Trivial case failed. Try for possible IDN domain-part
if value and u'@' in value:
parts = value.split(u'@')
domain_part = parts[-1]
try:
parts[-1] = parts[-1].encode('idna')
except UnicodeError:
raise e
super(EmailValidator, self).__call__(u'@'.join(parts))
else:
raise
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain
validate_email = EmailValidator(email_re, _(u'Enter a valid e-mail address.'), 'invalid')
so if you donβt want to use forms and form fields, you can import email_re
and use it in your function, or even better β import validate_email
and use it, catching possible ValidationError
.
def validateEmail( email ):
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
try:
validate_email( email )
return True
except ValidationError:
return False
And here is Mail::RFC822::Address regexp used in PERL, if you really need to be that paranoid.
228π
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
value = "foo.bar@baz.qux"
try:
validate_email(value)
except ValidationError as e:
print("bad email, details:", e)
else:
print("good email")
- [Django]-How do I import the Django DoesNotExist exception?
- [Django]-Loading initial data with Django 1.7+ and data migrations
- [Django]-Why does DEBUG=False setting make my django Static Files Access fail?
60π
Ick, no, please, donβt try to validate email addresses yourself. Itβs one of those things people never get right.
Your safest option, since youβre already using Django, is to just take advantage of its form validation for email. Per the docs:
>>> from django import forms
>>> f = forms.EmailField()
>>> f.clean('foo@example.com')
u'foo@example.com'
>>> f.clean(u'foo@example.com')
u'foo@example.com'
>>> f.clean('invalid e-mail address')
...
ValidationError: [u'Enter a valid e-mail address.']
- [Django]-How to get Request.User in Django-Rest-Framework serializer?
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-How to access array elements in a Django template?
7π
You got it wrong, but it is a task that you canβt do anyway. There is one and only one way to know if an RFC 2822 address is valid, and that is to send mail to it and get a response. Doing anything else doesnβt improve the information content of your datum by even a fractional bit.
You also screw the human factor and acceptance property, for when you give validateEmail
my address of
me+valid@mydomain.example.net
and you tell me Iβve made an error, I tell your application goodbye.
- [Django]-Django model "doesn't declare an explicit app_label"
- [Django]-How to define two fields "unique" as couple
- [Django]-Custom django admin templates not working
3π
I can see many answers here are based on django framework of python. But for verifying an email address why to install such an heavy software. We have the Validate_email package for Python that check if an email is valid, properly formatted and really exists. Its a light weight package (size < 1MB).
INSTALLATION :
pip install validate_email
Basic usage:
Checks whether email is in proper format.
from validate_email import validate_email
is_valid = validate_email('example@example.com')
To check the domain mx and verify email exists you can install the pyDNS package along with validate_email.
Verify email exists :
from validate_email import validate_email
is_valid = validate_email('example@example.com',verify=True)
Returns True if the email exist in real world else False.
- [Django]-Django abstract models versus regular inheritance
- [Django]-How do you perform Django database migrations when using Docker-Compose?
- [Django]-What is "load url from future" in Django
1π
This regex will validate an email address with reasonable accuracy.
\w[\w\.-]*@\w[\w\.-]+\.\w+
It allows alphanumeric characters, _
, .
and -
.
- [Django]-Bypass confirmation prompt for pip uninstall
- [Django]-How to reset db in Django? I get a command 'reset' not found error
- [Django]-How to reset Django admin password?
0π
Change your code from this:
re.match(β\b[\w.-]+@[\w.-]+.\w{2,4}\bβ, email)
to this:
re.match(rβ\b[\w.-]+@[\w.-]+.\w{2,4}\bβ, email)
works fine with me.
- [Django]-Django: Using F arguments in datetime.timedelta inside a query
- [Django]-Make the first letter uppercase inside a django template
- [Django]-How to implement followers/following in Django