在 Java 中验证电子邮件

发布于 2024-07-06 06:14:01 字数 325 浏览 6 评论 0原文

有什么方法可以在 Java 代码中验证电子邮件地址是否有效。 有效,我不仅仅意味着它的格式正确([email protected] ),但这就是一个真实的活动电子邮件地址。

我几乎可以肯定,没有 100% 可靠的方法可以做到这一点,因为这样的技术是垃圾邮件发送者梦寐以求的东西。 但也许有一些技术可以提供一些关于地址是否“真实”的有用指示。

Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format ([email protected]), but that's it's a real active e-mail address.

I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not.

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

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

发布评论

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

评论(9

自找没趣 2024-07-13 06:14:01

这是我周围的东西。 要检查地址格式是否有效,这里有一个正则表达式,用于验证它是否接近 rfc2822(它不会捕获一些奇怪的极端情况)。 我去年在网上找到的。

private static final Pattern rfc2822 = Pattern.compile(
        "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
);

if (!rfc2822.matcher(email).matches()) {
    throw new Exception("Invalid address");
}

这将处理简单的语法(大部分)。 我知道的另一项检查将让您检查域是否有 MX 记录。 看起来像这样:

Hashtable<String, String> env = new Hashtable<String, String>();

env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");

DirContext ictx = new InitialDirContext(env);

Attributes attrs = ictx.getAttributes(domainName, new String[] {"MX"});

Attribute attr = attrs.get("MX");

if (attr == null)
    // No MX record
else
    // If attr.size() > 0, there is an MX record

这个,我也是在网上找到的。 它来自此链接

如果这两项都通过,您就有很大机会获得有效地址。 至于地址是否是自己的(不仅仅是域名)、它不完整等等……你真的无法检查。

请注意,第二次检查时间密集。 它可能需要从几毫秒到 30 秒以上的时间(如果 DNS 没有响应并超时)。 这不是尝试为大量人员实时运行的东西。

希望这可以帮助。

编辑

我想指出的是,至少有更好的方法来代替正则表达式来检查基本有效性。 Don 和 Michael 指出 Apache Commons 有一些东西,我最近发现您可以在 InternetAddress 上使用 .validate() 来让 Java 检查该地址是否确实是 RFC-8222,这肯定比我的正则表达式更准确。

Here is what I have around. To check that the address is a valid format, here is a regex that verifies that it's nearly rfc2822 (it doesn't catch some weird corner cases). I found it on the 'net last year.

private static final Pattern rfc2822 = Pattern.compile(
        "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
);

if (!rfc2822.matcher(email).matches()) {
    throw new Exception("Invalid address");
}

That will take care of simple syntax (for the most part). The other check I know of will let you check if the domain has an MX record. It looks like this:

Hashtable<String, String> env = new Hashtable<String, String>();

env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");

DirContext ictx = new InitialDirContext(env);

Attributes attrs = ictx.getAttributes(domainName, new String[] {"MX"});

Attribute attr = attrs.get("MX");

if (attr == null)
    // No MX record
else
    // If attr.size() > 0, there is an MX record

This, I also found on the 'net. It came from this link.

If these both pass, you have a good chance at having a valid address. As for if the address it's self (not just the domain), it's not full, etc... you really can't check that.

Note that the second check is time intensive. It can take anywhere from milliseconds to >30 seconds (if the DNS does not respond and times out). It's not something to try and run real-time for large numbers of people.

Hope this helps.

EDIT

I'd like to point out that, at least instead of the regex, there are better ways to check basic validity. Don and Michael point out that Apache Commons has something, and I recently found out you can use .validate() on InternetAddress to have Java check that the address is really RFC-8222, which is certainly more accurate than my regex.

终陌 2024-07-13 06:14:01

您无法真正验证电子邮件是否存在,请在此处查看我对一个非常类似问题的回答:电子邮件 SMTP 验证器

You cannot really verify that an email exists, see my answer to a very similar question here: Email SMTP validator

幸福丶如此 2024-07-13 06:14:01

如果不发送电子邮件,可能很难获得 100% 的结果,但如果您在主机上进行 DNS 查找,至少应该告诉您它是一个可行的目标系统。

Without sending an email, it could be hard to get 100%, but if you do a DNS lookup on the host that should at least tell you that it is a viable destination system.

没企图 2024-07-13 06:14:01

Apache commons provides an email validator class too, which you can use. Simply pass your email address as an argument to isValid method.

平定天下 2024-07-13 06:14:01

对主机名进行 DNS 查找以查看该主机名是否存在。 理论上,您也可以启动与邮件服务器的连接,看看它是否告诉您收件人是否存在,但我认为许多服务器假装它们知道地址,然后无论如何都会拒绝电子邮件。

Do a DNS lookup on the hostname to see if that exists. You could theoretically also initiate a connection to the mailserver and see if it tells you whether the recipient exists, but I think many servers pretend they know an address, then reject the email anyway.

难以启齿的温柔 2024-07-13 06:14:01

您可以确定的唯一方法是实际发送邮件并让其阅读。

让您的注册过程有一个步骤,要求回复仅在电子邮件中找到的信息。 这是其他人所做的。

The only way you can be certain is by actually sending a mail and have it read.

Let your registration process have a step that requires responding to information found only in the email. This is what others do.

_畞蕅 2024-07-13 06:14:01

我不是 100% 确定,但是是否可以向邮件服务器发送 RCPT SMTP 命令来确定收件人是否有效? 检查有效 MX 主机比上面的建议更昂贵,但它也是最准确的。

I'm not 100% sure, but isn't it possible to send an RCPT SMTP command to a mail server to determine if the recipient is valid? It would be even more expensive than the suggestion above to check for a valid MX host, but it would also be the most accurate.

反目相谮 2024-07-13 06:14:01

如果您使用 GWT,则无法使用 InternetAddress,并且 MBCook 提供的模式非常可怕。

这是一个不那么可怕的正则表达式(可能不那么准确):

public static boolean isValidEmail(String emailAddress) {
    return emailAddress.contains(" ") == false && emailAddress.matches(".+@.+\\.[a-z]+");
}

If you're using GWT, you can't use InternetAddress, and the pattern supplied by MBCook is pretty scary.

Here is a less scary regex (might not be as accurate):

public static boolean isValidEmail(String emailAddress) {
    return emailAddress.contains(" ") == false && emailAddress.matches(".+@.+\\.[a-z]+");
}
自此以后,行同陌路 2024-07-13 06:14:01
public static boolean isValidEmail(String emailAddress) {
    return emailAddress.contains(" ") == false && emailAddress.matches(".+@.+\\.[a-z]+");
} 
public static boolean isValidEmail(String emailAddress) {
    return emailAddress.contains(" ") == false && emailAddress.matches(".+@.+\\.[a-z]+");
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文