在django / python中检查电子邮件的有效性

我编写了一个向新闻稿库添加电子邮件的功能。直到我添加了已发送电子邮件的有效性检查,它都可以正常工作。现在,每次我得到“错误的电子邮件”作为回报。有人可以在这里看到任何错误吗?使用的正则表达式为:

\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

回答:

这是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

以上是 在django / python中检查电子邮件的有效性 的全部内容, 来源链接: utcz.com/qa/418471.html

回到顶部