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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (191)

我已经写了一个函数来添加电子邮件到通讯基地。在我添加检查发送的电子邮件的有效性之前,它的工作完美无瑕。现在每次我收到“错误的电子邮件”。任何人都可以在这里看到任何错误?使用的正则表达式是:

\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b它是100%有效的,但我可能会使用它错误,或者它可能是一些逻辑错误:

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
提问于
用户回答回答于
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
try:
    validate_email("foo.bar@baz.qux")
except ValidationError as e:
    print "oops! wrong email"
else:
    print "hooray! email is valid"

扫码关注云+社区

领取腾讯云代金券