是否有一个好方法来检查表单输入使用正则表达式,以确保它是一个正确的风格的电子邮件地址?从昨晚开始搜索,每个人都回答了关于这个话题的问题,如果它是一个子域名的电子邮件地址,似乎也有问题。


当前回答

电子邮件地址并不像看上去那么简单!例如,Bob_O'Reilly+tag@example.com是一个有效的电子邮件地址。

我在lepl包(http://www.acooke.org/lepl/)上有一些运气。它可以验证RFC 3696中指出的电子邮件地址:http://www.faqs.org/rfcs/rfc3696.html

找到一些旧代码:

import lepl.apps.rfc3696
email_validator = lepl.apps.rfc3696.Email()
if not email_validator("email@example.com"):
    print "Invalid email"

其他回答

电子邮件地址非常复杂。下面是一个匹配每个rfc822有效地址的示例正则表达式: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

您会注意到它可能比程序的其他部分要长。甚至还有用于验证电子邮件地址的Perl完整模块。所以你可能不会得到任何东西,100%完美的正则表达式,同时也可读。下面是一个递归下降解析器示例: http://cpansearch.perl.org/src/ABIGAIL/RFC-RFC822-Address-2009110702/lib/RFC/RFC822/Address.pm

但是您需要决定是需要完美的解析还是简单的代码。

检查电子邮件使用email_validator

from email_validator import validate_email, EmailNotValidError

def check_email(email):
    try:
        v = validate_email(email)  # validate and get info
        email = v["email"]  # replace with normalized form
        print("True")
    except EmailNotValidError as e:
        # email is not valid, exception message is human-readable
        print(str(e))

check_email("test@gmailcom")
import re
def email():
    email = raw_input("enter the mail address::")
     match = re.search(r'[\w.-]+@[\w.-]+.\w+', email)

    if match:
        print "valid email :::", match.group()
    else:
        print "not valid:::"

email()

The only really accurate way of distinguishing real, valid email addresses from invalid ones is to send mail to it. What counts as an email is surprisingly convoluted ("John Doe" <john.doe@example.com>" actually is a valid email address), and you most likely want the email address to actually send mail to it later. After it passes some basic sanity checks (such as in Thomas's answer, has an @ and at least one . after the @), you should probably just send an email verification letter to the address, and wait for the user to follow a link embedded in the message to confirm that the email was valid.

我还没有在这里的一堆自定义正则表达式答案中看到答案,但是……

存在一个名为py3-validate-email validate_email的python库,它有3个级别的电子邮件验证,包括询问有效的SMTP服务器电子邮件地址是否有效(不发送电子邮件)。

安装

python -m pip install py3-validate-email

基本用法:

from validate_email import validate_email
is_valid = validate_email(email_address='example@example.com', \
    check_regex=True, check_mx=True, \
    from_address='my@from.addr.ess', helo_host='my.host.name', \ 
    smtp_timeout=10, dns_timeout=10, use_blacklist=True)

对于那些对肮脏细节感兴趣的人,validate_email.py (source)旨在忠实于RFC 2822。

我们所做的只是将输入字符串与1进行比较 庞大的正则表达式。但是构建那个regexp 通过组装它,可以更容易地确保其正确性 从RFC定义的“令牌”。每一个符号都是 在附带的单元测试文件中测试。


你可能需要pyDNS模块来检查SMTP服务器

pip install pyDNS

或者来自Ubuntu

apt-get install python3-dns