用Django/python检查电子邮件的有效性

2024-09-25 06:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写了一个功能,添加电子邮件到时事通讯基地。在我添加了检查发送电子邮件的有效性之前,它的工作是完美无缺的。现在每次我收到“错误的电子邮件”作为回报。有人看到这里有什么错误吗?使用的regex是:

\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b并且它是100%有效的(http://gskinner.com/RegExr/),但是我可能使用错误,或者可能是一些逻辑错误:

def newsletter_add(request):
    if request.method == "POST":   
        try:
            e = NewsletterEmails.objects.get(email = request.POST['email'])
            message = _(u"Email is already added.")
            type = "error"
        except NewsletterEmails.DoesNotExist:
            if validateEmail(request.POST['email']):
                try:
                    e = NewsletterEmails(email = request.POST['email'])
                except DoesNotExist:
                    pass
                message = _(u"Email added.")
                type = "success"
                e.save()
            else:
                message = _(u"Wrong email")
                type = "error"

import re

def validateEmail(email):
    if len(email) > 6:
        if re.match('\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b', email) != None:
            return 1
    return 0

Tags: messageaddedif电子邮件emailrequestdeftype
3条回答
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")

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: https://github.com/django/django/blob/master/django/core/validators.py#L168-L180

这是django.core.validators的一部分,您可能会发现它很有趣:)

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')

因此,如果不想使用表单和表单域,可以导入email_re并在函数中使用它,或者更好的方法是导入validate_email并使用它,捕获可能的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

这里是PERL中使用的Mail::RFC822::Address regexp,如果您真的需要那么多疑的话。

Ick,不,请不要自己验证电子邮件地址。这是人们永远不会做对的事情之一。

既然您已经在使用Django,那么您最安全的选择就是利用它对电子邮件的表单验证。根据文档(http://docs.djangoproject.com/en/dev/ref/forms/fields/):

>>> 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.']

相关问题 更多 >