如何通过在java中发送邮件来验证电子邮件地址是否确实存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9848972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to verify an email address really exists by sending a mail in java
提问by Kanchan Ruia
Our web application sends email to every user who enters their email id. But how can i make sure that email id entered by user is valid one.Actually what we do when any user enters a email id we send link to his email id to activate the acount. I have a code for sending emails. But it doesnot give me any errors even if mail id does not exists. Will you please tell me how to solve the problem ? If email id does not exists really it should give some error.
我们的 Web 应用程序向每个输入其电子邮件 ID 的用户发送电子邮件。但是我如何确保用户输入的电子邮件 ID 是有效的。实际上,当任何用户输入电子邮件 ID 时,我们都会发送指向他的电子邮件 ID 的链接以激活帐户。我有一个发送电子邮件的代码。但即使邮件 ID 不存在,它也不会给我任何错误。你能告诉我如何解决这个问题吗?如果电子邮件 ID 确实不存在,它应该给出一些错误。
I am here attaching my code
我在这里附上我的代码
package csv;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class email {
public void send(String recipeintEmail,
String subject,
String messageText,String[] attachments)
throws MessagingException, AddressException {
/*
It is a good practice to put this in a java.util.Properties
file and encrypt password. Scroll down
to comments below to see
how to use java.util.Properties in JSF context.
*/
String senderEmail = "our email address";
String senderMailPassword = "password";
String gmail = "smtp.gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.user", senderEmail);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
// Required to avoid security exception.
email.MyAuthenticator authentication =
new email.MyAuthenticator(senderEmail,senderMailPassword);
Session session =
Session.getDefaultInstance(props,authentication);
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(messageText);
// Add message text
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Attachments should reside in your server.
// Example "c:\file.txt" or "/home/user/photo.jpg"
for (int i=0; i < attachments.length; i++) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachments[i]);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachments [i]);
multipart.addBodyPart(messageBodyPart) ;
}
message.setContent(multipart);
message.setSubject(subject);
message.setFrom(new InternetAddress(senderEmail));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(recipeintEmail));
Transport transport = session.getTransport("smtps");
transport.connect(gmail,465, senderEmail, senderMailPassword);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
private class MyAuthenticator extends javax.mail.Authenticator {
String User;
String Password;
public MyAuthenticator (String user, String password) {
User = user;
Password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(User, Password);
}
}
public static void main(String args[]) throws MessagingException
{
// email e=new email();
// String at[]={"c:/COPYRIGHT.txt"};
// e.send("[email protected]", "hello","test" )");
}
}
回答by ring bearer
There is no fool-proof way to do this. You may try steps explained in this blog postbut it is not guaranteed to work with all kinds of mail server/relay set up.
没有万无一失的方法来做到这一点。您可以尝试本博客文章中介绍的步骤,但不能保证适用于所有类型的邮件服务器/中继设置。
Send the user an activation key along with the URL and that will make it necessary to provide a valid email id if the user wants to log in/use what you are providing.
向用户发送激活密钥和 URL,如果用户想要登录/使用您提供的内容,则必须提供有效的电子邮件 ID。
回答by Justin Helmig
If you are going to stick with sending emails to validate, I would encourage you to make it veryclear you will send an email validation link prior to allowing the user to access whatever they are registering for to reduce the number of bogus email addresses. We have done testing and some small changes in the registration form labels dropped our invalid email rate significantly.
如果你要坚持发送电子邮件来验证,我会鼓励你做它很清楚,你将允许用户访问任何他们报名参加,以减少虚假的电子邮件地址的号码之前,发送电子邮件验证链接。我们已经进行了测试,注册表标签中的一些小变化显着降低了我们的无效电子邮件率。
One word of warning. If you are using sending emails to verify if an email is valid and you are sending a large quantity of emails to invalid addresses, especially on consumer oriented domains (e.g. Yahoo, GMail, AOL, etc), you risk being flagged as a spammer since hard bounces (sending to an invalid address) will affect your reputation score. I wrote a blog entry on the different ways to validate emailsa few months ago for both free and commercial ways to verify your registrants that may be useful.
一句警告。如果您使用发送电子邮件来验证电子邮件是否有效,并且您将大量电子邮件发送到无效地址,尤其是在面向消费者的域(例如 Yahoo、GMail、AOL 等)上,则您可能会被标记为垃圾邮件发送者,因为硬退回(发送到无效地址)会影响您的声誉评分。几个月前,我写了一篇关于验证电子邮件的不同方法的博客文章,以免费和商业方式验证您的注册人可能有用。
回答by Rituraj Rathore
You can use java mail API to validate the email.
您可以使用 java 邮件 API 来验证电子邮件。
try {
//
// Create InternetAddress object and validated the supplied
// address which is this case is an email address.
InternetAddress internetAddress = new InternetAddress(email);
internetAddress.validate();
isValid = true;
}
catch (AddressException e) {
System.out.println("You are in catch block -- Exception Occurred for: " + email);
}
You can download java Mail APIs from http://www.oracle.com/technetwork/java/index-138643.html
您可以从http://www.oracle.com/technetwork/java/index-138643.html下载 java Mail APIs
回答by Brainhash
One way of resolving this could be to track bounced message. But this approach has several difficulties due to uneven standards.
解决此问题的一种方法可能是跟踪退回的消息。但是由于标准不均,这种方法有几个困难。
Yet it might be worth doing something over nothing. At times it gets important to know if user has received email and is not responding OR the email address itself is incorrect.
然而,无所事事地做点什么可能是值得的。有时,了解用户是否收到电子邮件但没有回复或电子邮件地址本身不正确变得很重要。
You might want to check this link: http://www.oracle.com/technetwork/java/faq-135477.html#bounce
您可能想查看此链接:http: //www.oracle.com/technetwork/java/faq-135477.html#bounce
See this excerpt from link:
请参阅以下链接的摘录:
Q: When a message can't be delivered, a failure message is returned. How can I detect these "bounced" messages?
Q:当无法投递消息时,返回失败消息。如何检测这些“退回”的消息?
A: While there is an Internet standard for reporting such errors (the multipart/report MIME type, see RFC1892), it is not widely implemented yet. RFC1211 discusses this problem in depth, including numerous examples.
答:虽然有报告此类错误的 Internet 标准(multipart/report MIME 类型,请参阅 RFC1892),但尚未广泛实施。RFC1211 深入讨论了这个问题,包括许多示例。
In Internet email, the existence of a particular mailbox or user name can only be determined by the ultimate server that would deliver the message. The message may pass through several relay servers (that are not able to detect the error) before reaching the end server.
在 Internet 电子邮件中,特定邮箱或用户名的存在只能由将传递邮件的最终服务器确定。消息在到达最终服务器之前可能会通过多个中继服务器(无法检测到错误)。
Typically, when the end server detects such an error, it will return a message indicating the reason for the failure to the sender of the original message. There are many Internet standards covering such Delivery Status Notifications but a large number of servers don't support these new standards, instead using ad hoc techniques for returning such failure messages.
通常,当端服务器检测到此类错误时,它会向原始消息的发送方返回一条消息,指出失败的原因。有许多 Internet 标准涵盖此类传递状态通知,但大量服务器不支持这些新标准,而是使用临时技术返回此类失败消息。
This makes it very difficult to correlate a "bounced" message with the original message that caused the problem. (Note that this problem is completely independent of JavaMail.) JavaMail now includes support for parsing Delivery Status Notifications; see the NOTES.txt file in the JavaMail package for details.
这使得很难将“退回的”消息与导致问题的原始消息相关联。(注意这个问题完全独立于 JavaMail。)JavaMail 现在包括对解析传递状态通知的支持;有关详细信息,请参阅 JavaMail 包中的 NOTES.txt 文件。
There are a number of techniques and heuristics for dealing with this problem - none of them perfect. One technique is Variable Envelope Return Paths, described at http://cr.yp.to/proto/verp.txt.
有许多技术和启发式方法可以处理这个问题——它们都不是完美的。一种技术是可变信封返回路径,描述于http://cr.yp.to/proto/verp.txt。