在 django/python 中检查电子邮件的有效性 [英] Checking validity of email in django/python
问题描述
我编写了一个将电子邮件添加到时事通讯库的函数.直到我添加了检查已发送电子邮件的有效性之前,它才能正常工作.现在每次我收到错误的电子邮件"作为回报.有人能在这里看到任何错误吗?使用的正则表达式是:
I have written a function for adding emails to newsletter base. Until I've added checking validity of sent email it was working flawlessly. Now each time I'm getting "Wrong email" in return. Can anybody see any errors here ? The regex used is :
[w.-]+@[w.-]+.w{2,4}
并且它是 100% 有效的(http://gskinner.com/RegExr/),但可能是我用错了,也可能是逻辑错误:
[w.-]+@[w.-]+.w{2,4}
and it is 100% valid (http://gskinner.com/RegExr/), but I may be using it wrong, or it may be some logic error :
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('[w.-]+@[w.-]+.w{2,4}', email) != None:
return 1
return 0
推荐答案
UPDATE 2017:以下代码已有 7 年历史,并且经过修改、修复和扩展.对于现在希望这样做的人,正确的代码位于 此处.
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.
这里是 django.core.validators 的一部分,你可能会觉得有趣:)
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'|^"([ 01- 10 13 14 16- 37!#-[]-177]|\[ 01-011 13 14 16-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
.
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
这里是 Mail::RFC822::Address regexp 在 PERL 中使用,如果您真的需要成为那种偏执狂.
And here is Mail::RFC822::Address regexp used in PERL, if you really need to be that paranoid.
这篇关于在 django/python 中检查电子邮件的有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!