tags:

views:

162

answers:

4

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?

+1  A: 

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.

Dustin Laine
But mistyping an email will not always fail a regex validation. Example: [email protected]. +1 for the link though.
Joel Potter
@Joel Potter, that is why I specified the process as a replacement to him goal. The confirmation is a good feature for more than accuracy, it is also useful in eliminating bots.
Dustin Laine
Thanks for the link. I already use regex to verify this. Still doesn't guard against non-existent domains though.
Mario
A: 

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?

Yoopergeek
Not only that, but mail hosts are not required to have an A record (IP address), only an MX record.
Greg Hewgill
Ooooh, that's a good point.
Yoopergeek
+3  A: 

The most reliable way to make sure a mail server is actually configured for a given domain is to query the MX record for that domain.

Eric J.
The link you refer to works, thanks. The code uses DllImport though, which I am not too keen on.
Mario
There is probably a 100% managed solution out there if you don't want to reference any unmanaged code.
Eric J.
A: 

Try something like this:

string email = "[email protected]"
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
Eric Petroelje