如何检查有效的电子邮件地址?

发布于 2024-12-14 06:42:27 字数 99 浏览 3 评论 0 原文

有没有一种好方法可以使用正则表达式检查表单输入以确保它是正确样式的电子邮件地址?从昨晚开始就一直在搜索,如果它是子域名电子邮件地址,那么每个回答过人们有关该主题的问题的人似乎也有问题。

Is there a good way to check a form input using regex to make sure it is a proper style email address? Been searching since last night and everybody that has answered peoples questions regarding this topic also seems to have problems with it if it is a subdomained email address.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

伤感在游骋 2024-12-21 06:42:27

没有意义。即使您可以验证电子邮件地址在语法上是有效的,您仍然需要检查它是否没有输入错误,以及它是否确实发送给您认为的人。唯一的方法是向他们发送一封电子邮件并让他们单击链接进行验证。

因此,最基本的检查(例如,他们没有意外输入街道地址)通常就足够了。例如:它恰好有一个 @ 符号,并且在 @ 之后的部分中至少有一个 .

[^@]+@[^@]+\.[^@]+

您可能还想禁止空格——可能存在包含空格的有效电子邮件地址,但我从未见过,所以这很可能是用户错误。

如果您想要完整检查,请查看此问题< /a>.


更新:以下是使用任何此类正则表达式的方法:

import re

if not re.match(r"... regex here ...", email):
  # whatever

Python ≥3.4 有 re.fullmatch 优于 re.match

注意字符串前面的r;这样,你就不需要两次逃避事情了。

如果要检查大量正则表达式,首先编译正则表达式可能会更快:

import re

EMAIL_REGEX = re.compile(r"... regex here ...")

if not EMAIL_REGEX.match(email):
  # whatever

另一种选择是使用 validate_email 包,它实际上联系 SMTP 服务器以验证该地址是否存在。但这仍然不能保证它属于正确的人。

There is no point. Even if you can verify that the email address is syntactically valid, you'll still need to check that it was not mistyped, and that it actually goes to the person you think it does. The only way to do that is to send them an email and have them click a link to verify.

Therefore, a most basic check (e.g. that they didn't accidentally entered their street address) is usually enough. Something like: it has exactly one @ sign, and at least one . in the part after the @:

[^@]+@[^@]+\.[^@]+

You'd probably also want to disallow whitespace -- there are probably valid email addresses with whitespace in them, but I've never seen one, so the odds of this being a user error are on your side.

If you want the full check, have a look at this question.


Update: Here's how you could use any such regex:

import re

if not re.match(r"... regex here ...", email):
  # whatever

Python ≥3.4 has re.fullmatch which is preferable to re.match.

Note the r in front of the string; this way, you won't need to escape things twice.

If you have a large number of regexes to check, it might be faster to compile the regex first:

import re

EMAIL_REGEX = re.compile(r"... regex here ...")

if not EMAIL_REGEX.match(email):
  # whatever

Another option is to use the validate_email package, which actually contacts the SMTP server to verify that the address exists. This still doesn't guarantee that it belongs to the right person, though.

臻嫒无言 2024-12-21 06:42:27

Python标准库带有电子邮件解析功能: email.utils.parseaddr()

它返回一个包含真实姓名和电子邮件的实际地址部分的二元组:

>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')

>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')

>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')

如果解析不成功,它返回一个空字符串二元组:

>>> parseaddr('[invalid!email]')
('', '')

该解析器的一个问题是它接受任何被认为是 RFC-822 和朋友的有效电子邮件地址,包括许多显然无法在广泛的互联网上寻址的内容:

>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')

>>> parseaddr('invalid-email')
('', 'invalid-email')

因此,正如 @TokenMacGuy 所说,检查电子邮件地址的唯一确定方法就是发送一封电子邮件到预期的地址,并等待用户根据邮件中的信息采取行动。

但是,您可能至少需要检查第二个元组元素上是否存在 @ 符号,如 @bvukelic 建议的那样:

>>> '@' in parseaddr("invalid-email")[1]
False

如果您想更进一步,可以安装 dnspython 项目并解析电子邮件域的邮件服务器(“@”后面的部分),仅尝试发送电子邮件- 如果有实际邮件MX 服务器:

>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NXDOMAIN

您可以通过捕获 dns.exception.DNSException 来捕获 NoAnswerNXDOMAIN

是的,foo@[电子邮件受保护]是语法上有效的地址。仅应考虑最后一个 @ 来检测域部分的开始位置。

The Python standard library comes with an e-mail parsing function: email.utils.parseaddr().

It returns a two-tuple containing the real name and the actual address parts of the e-mail:

>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')

>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')

>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')

And if the parsing is unsuccessful, it returns a two-tuple of empty strings:

>>> parseaddr('[invalid!email]')
('', '')

An issue with this parser is that it's accepting of anything that is considered as a valid e-mail address for RFC-822 and friends, including many things that are clearly not addressable on the wide Internet:

>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')

>>> parseaddr('invalid-email')
('', 'invalid-email')

So, as @TokenMacGuy put it, the only definitive way of checking an e-mail address is to send an e-mail to the expected address and wait for the user to act on the information inside the message.

However, you might want to check for, at least, the presence of an @-sign on the second tuple element, as @bvukelic suggests:

>>> '@' in parseaddr("invalid-email")[1]
False

If you want to go a step further, you can install the dnspython project and resolve the mail servers for the e-mail domain (the part after the '@'), only trying to send an e-mail if there are actual MX servers:

>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NXDOMAIN

You can catch both NoAnswer and NXDOMAIN by catching dns.exception.DNSException.

And Yes, foo@[email protected] is a syntactically valid address. Only the last @ should be considered for detecting where the domain part starts.

甜味超标? 2024-12-21 06:42:27

我还没有在混乱的自定义正则表达式答案中看到答案,但是......

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

安装

python -m pip install py3-validate-email

基本用法:

from validate_email import validate_email
is_valid = validate_email(email_address='[email protected]', \
    check_regex=True, check_mx=True, \
    from_address='[email protected]', helo_host='my.host.name', \ 
    smtp_timeout=10, dns_timeout=10, use_blacklist=True)

对于那些对脏细节感兴趣的人,validate_email.py (source< /a>) 旨在忠实于 RFC第2822章

我们真正要做的就是将输入字符串与一个进行比较
巨大的正则表达式。但是构建正则表达式,并且
确保其正确性,通过组装变得更加容易
来自 RFC 定义的“令牌”。这些令牌中的每一个都是
在随附的单元测试文件中进行了测试。


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

pip install pyDNS

或来自 Ubuntu

apt-get install python3-dns

I haven't seen the answer already here among the mess of custom Regex answers, but...

There exists a python library called py3-validate-email validate_email which has 3 levels of email validation, including asking a valid SMTP server if the email address is valid (without sending an email).

To install

python -m pip install py3-validate-email

Basic usage:

from validate_email import validate_email
is_valid = validate_email(email_address='[email protected]', \
    check_regex=True, check_mx=True, \
    from_address='[email protected]', helo_host='my.host.name', \ 
    smtp_timeout=10, dns_timeout=10, use_blacklist=True)

For those interested in the dirty details, validate_email.py (source) aims to be faithful to RFC 2822.

All we are really doing is comparing the input string to one
gigantic regular expression. But building that regexp, and
ensuring its correctness, is made much easier by assembling it
from the "tokens" defined by the RFC. Each of these tokens is
tested in the accompanying unit test file.


you may need the pyDNS module for checking SMTP servers

pip install pyDNS

or from Ubuntu

apt-get install python3-dns

对岸观火 2024-12-21 06:42:27

电子邮件地址并不像看起来那么简单!例如,Bob_O'[email protected] 是有效的电子邮件地址。

我对 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 protected]"):
    print "Invalid email"

Email addresses are not as simple as they seem! For example, Bob_O'[email protected], is a valid email address.

I've had some luck with the lepl package (http://www.acooke.org/lepl/). It can validate email addresses as indicated in RFC 3696: http://www.faqs.org/rfcs/rfc3696.html

Found some old code:

import lepl.apps.rfc3696
email_validator = lepl.apps.rfc3696.Email()
if not email_validator("[email protected]"):
    print "Invalid email"
百合的盛世恋 2024-12-21 06:42:27

我找到了一种很好的(并且经过测试的)方法来检查有效的电子邮件地址。我将我的代码粘贴在这里:

# here i import the module that implements regular expressions
import re

# here is my function to check for valid email address
def test_email(your_pattern):
  pattern = re.compile(your_pattern)
  # here is an example list of email to check it at the end
  emails = ["[email protected]", "[email protected]", "wha.t.`1an?ug{}[email protected]"]
  for email in emails:
    if not re.match(pattern, email):
        print "You failed to match %s" % (email)
    elif not your_pattern:
        print "Forgot to enter a pattern!"
    else:
        print "Pass"

# my pattern that is passed as argument in my function is here!
pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"   

# here i test my function passing my pattern
test_email(pattern)

I found an excellent (and tested) way to check for valid email address. I paste my code here:

# here i import the module that implements regular expressions
import re

# here is my function to check for valid email address
def test_email(your_pattern):
  pattern = re.compile(your_pattern)
  # here is an example list of email to check it at the end
  emails = ["[email protected]", "[email protected]", "wha.t.`1an?ug{}[email protected]"]
  for email in emails:
    if not re.match(pattern, email):
        print "You failed to match %s" % (email)
    elif not your_pattern:
        print "Forgot to enter a pattern!"
    else:
        print "Pass"

# my pattern that is passed as argument in my function is here!
pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"   

# here i test my function passing my pattern
test_email(pattern)
相守太难 2024-12-21 06:42:27

我在这里看到很多复杂的答案。其中一些人无法了解简单、真实的电子邮件地址,或者存在误报。下面是测试该字符串是否为有效电子邮件的最简单方法。它针对 2 个和 3 个字母的 TLD 进行测试。现在从技术上来说您可以拥有更大的数量,您可能希望将 3 个增加到 4 个、5 个甚至 10 个。

import re
def valid_email(email):
  return bool(re.search(r"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", email))

I see a lot of complicated answers here. Some of them, fail to knowledge simple, true email address, or have false positives. Below, is the simplest way of testing that the string would be a valid email. It tests against 2 and 3 letter TLD's. Now that you technically can have larger ones, you may wish to increase the 3 to 4, 5 or even 10.

import re
def valid_email(email):
  return bool(re.search(r"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", email))
岁月静好 2024-12-21 06:42:27

这通常可以使用正则表达式来解决。然而,解决方案有很多变化。取决于您需要的严格程度,以及您是否有验证的自定义要求,或者是否接受任何有效的电子邮件地址。

请参阅此页面以供参考:http://www.regular-expressions.info/email.html

This is typically solved using regex. There are many variations of solutions however. Depending on how strict you need to be, and if you have custom requirements for validation, or will accept any valid email address.

See this page for reference: http://www.regular-expressions.info/email.html

红尘作伴 2024-12-21 06:42:27

电子邮件地址非常复杂。下面是一个示例正则表达式,它将匹配每个 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 addresses are incredibly complicated. Here's a sample regex that will match every RFC822-valid address:
http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

You'll notice that it's probably longer than the rest of your program. There are even whole modules for Perl with the purpose of validating email addresses. So you probably won't get anything that's 100% perfect as a regex while also being readable. Here's a sample recursive descent parser:
http://cpansearch.perl.org/src/ABIGAIL/RFC-RFC822-Address-2009110702/lib/RFC/RFC822/Address.pm

but you'll need to decide whether you need perfect parsing or simple code.

第几種人 2024-12-21 06:42:27
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()
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()
故事↓在人 2024-12-21 06:42:27
from validate_email import validate_email
is_valid = validate_email('[email protected]',verify=True)
print(bool(is_valid))

请参阅 validate_email 文档

from validate_email import validate_email
is_valid = validate_email('[email protected]',verify=True)
print(bool(is_valid))

See validate_email docs.

三岁铭 2024-12-21 06:42:27

如果您想从长字符串或文件中取出邮件,请尝试此操作。

([^@|\s]+@[^@]+\.[^@|\s]+)

请注意,当您的电子邮件地址前后有空格时,此功能才有效。如果你没有空间或者有一些特殊字符那么你可以尝试修改它。

工作示例:

string="Hello ABCD, here is my mail id [email protected] "
res = re.search("([^@|\s]+@[^@]+\.[^@|\s]+)",string,re.I)
res.group(1)

这将取出 [email protected] 来自该字符串。

另外,请注意,这可能不是正确的答案...但我将其发布在这里是为了帮助像我这样有特定要求的人

If you want to take out the mail from a long string or file Then try this.

([^@|\s]+@[^@]+\.[^@|\s]+)

Note, this will work when you have a space before and after your email-address. if you don't have space or have some special chars then you may try modifying it.

Working example:

string="Hello ABCD, here is my mail id [email protected] "
res = re.search("([^@|\s]+@[^@]+\.[^@|\s]+)",string,re.I)
res.group(1)

This will take out [email protected] from this string.

Also, note this may not be the right answer... But I have posted it here to help someone who has specific requirement like me

你没皮卡萌 2024-12-21 06:42:27

要检查电子邮件,请使用 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")

For check of email use 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")
悸初 2024-12-21 06:42:27
"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$"
"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$"
给妤﹃绝世温柔 2024-12-21 06:42:27

发现这是一个实际的实现:

^[^@\s]+@[^@\s]+\.[^@\s]+$

Found this to be a practical implementation:

^[^@\s]+@[^@\s]+\.[^@\s]+$
猛虎独行 2024-12-21 06:42:27

查找电子邮件 ID:
查找IP截图

import re 
a=open("aa.txt","r")
#c=a.readlines() 
b=a.read()
c=b.split("\n")
print(c)
  for d in c: 
    obj=re.search(r'[\w.]+\@[\w.]+',d)
    if obj:
      print(obj.group())  
#for more calcification click on image above..

Finding Email-id:
finding IP screenshot

import re 
a=open("aa.txt","r")
#c=a.readlines() 
b=a.read()
c=b.split("\n")
print(c)
  for d in c: 
    obj=re.search(r'[\w.]+\@[\w.]+',d)
    if obj:
      print(obj.group())  
#for more calcification click on image above..
篱下浅笙歌 2024-12-21 06:42:27

在电子邮件输入上使用此过滤器掩码:
emailMask: /[\w.\-@'"!#$%&'*+/=?^_{|}~]/i`

Use this filter mask on email input:
emailMask: /[\w.\-@'"!#$%&'*+/=?^_{|}~]/i`

俏︾媚 2024-12-21 06:42:27

电子邮件验证

import re
def validate(email): 
    match=re.search(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9.]*\.*[com|org|edu]{3}$)",email)
    if match:
        return 'Valid email.'
    else:
        return 'Invalid email.'

email validation

import re
def validate(email): 
    match=re.search(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9.]*\.*[com|org|edu]{3}$)",email)
    if match:
        return 'Valid email.'
    else:
        return 'Invalid email.'
老娘不死你永远是小三 2024-12-21 06:42:27

区分真实有效电子邮件地址和无效电子邮件地址的唯一真正准确的方法是向其发送邮件。电子邮件的含义令人惊讶地复杂("John Doe" <[email] protected]>" 实际上是一个有效的电子邮件地址),并且您很可能希望该电子邮件地址在通过一些基本的健全性检查后实际向其发送邮件(例如在托马斯的回答中,有一个 @ 和至少一个 )。 >.@ 之后),您可能应该只向该地址发送一封电子邮件验证信,然后等待用户点击消息中嵌入的链接来确认该电子邮件是有效的。

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" <[email protected]>" 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文