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
UPDATE 2017 : 아래 코드는 7 년이 지났으며 이후 수정, 수정 및 확장되었습니다. 지금이 작업을 수행하려는 사람을 위해 올바른 코드가 여기에 있습니다. 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 가 있습니다.
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를 사용하고 있으므로 가장 안전한 옵션은 이메일에 대한 양식 유효성 검사를 이용하는 것입니다. 문서에 따라 ( 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.']
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.
This regex will validate an email address with reasonable accuracy.
\w[\w\.-]*@\w[\w\.-]+\.\w+
It allows alphanumeric characters, _
, .
and -
.
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.
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.
참고URL : https://stackoverflow.com/questions/3217682/checking-validity-of-email-in-django-python
'Programing' 카테고리의 다른 글
업로드되는 dropzone.js 파일 수를 제한하는 방법은 무엇입니까? (0) | 2020.11.06 |
---|---|
UIButton 제목 정렬 및 여러 줄 지원 (0) | 2020.11.06 |
목록을 얻는 방법 (0) | 2020.11.06 |
XOR 변수 스와핑은 어떻게 작동합니까? (0) | 2020.11.06 |
ClearCase 장점 / 단점 (0) | 2020.11.06 |