简体   繁体   中英

How to know a domain is bad before calling SmtpClient.Send()?

I have code that sends emails to users from a signup webpage. Occasionally, users will mistype an email address and the address ends up having a bad domain.

I would love to be able to check to see if the domain is bad BEFORE calling the System.Net.Mail.SmtpClient.Send() method since this would lead to a better user experience. I think using AJAX to tell the user right away their email won't send without having to programmatically send an email before finding out it is bad is much more elegant.

I currently handle the error just fine so please don't discuss how to handle errors. The error I get is: "Mailbox unavailable. The server response was: : Recipient address rejected: Domain not found"

Does anyone know of a way that would use similar (or the same exact) code to verify if a domain is bad or not before calling the Send() method?

确保为给定域实际配置邮件服务器的最可靠方法是查询该的MX记录

Try something like this:

string email = "person@domain.com"
MailAddress ma = new MailAddress(email); // Throws exception if email address is incorrectly formatted
System.Net.Dns.GetHostEntry(ma.Host); // Throws exception if host is invalid

Here is a good article on it: http://www.codeproject.com/KB/validation/Valid_Email_Addresses.aspx

In my experience I just use a regex validator to verify format and use a confirmation type of system to ensure it is a valid address.

UPDATE: That article is old, so I would check to ensure not deprecated.

Perhaps use System.Net.Dns.GetHostByName(hostname) and determine if it comes back with something valid?

Although MSDN is telling me that that method is deprecated...

Maybe System.Net.Dns.GetHostEntry(hostname) is it's predecessor?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM