ASP.Net - sending emails

389 Views Asked by At

I am sending email from within the web application using NetMail and it works fine when there is nothing wrong! I am trying to catch some of the errors, specifically wrong email address that should cause an exception but it seems it doesn't. My email address is fisrstname.dot.middleinitial.lastname@domain_name. I don't include middle initial on purpose to cause an error but when I trace the code it goes through. This is what I have:

SmtpClient sc = new SmtpClient(<Mail_relay>);
sc.Credentials = new NetworkCredential();

try
{
    sc.Send(mm);
}
catch (SmtpFailedRecipientsException FRE)  
{                          
    foreach (SmtpFailedRecipientException smtpFailedRecipientException in FRE.InnerExceptions)  
    {  
        // Get the email that is causing the exception  
        string sFailedRecipient = smtpFailedRecipientException.FailedRecipient;

        // Get the status code  
        SmtpStatusCode sc = FRE.StatusCode;  
    }  
}  
catch (SmtpException smtpEx)
{
    SmtpStatusCode sc = smtpEx.StatusCode;
}
catch (Exception generalEx)
{
    string sMessage = generalEx.Message;
}

I thought bad email address would be caught in the first catch block but it is not, it just goes right through all catch blocks.

2

There are 2 best solutions below

4
On BEST ANSWER

Basically this is due to how SMTP works. What you have to realize is that when using SMTP as the message transport, the catch section of your code is typically only going to fire if the server that your machine is trying to hand off the message to does not accept the message and returns a valid status, or there is a communication error while sending. Depending on what machine you are sending from (meaning where it lives in your netowkr organization, etc), this may be all you can reliably count on.

The key is that the server your machine is attempting to hand off the message to may not be the server which contains the inbox to which the message should be delivered; or the destination SMTP server does not validate it during communication (yes, that is possible). In the latter case, the message is bounced asynchronously from your initial communication attempt. This is because there are many mail servers which simply accept incoming messages as quickly as possible with pretty minimal validation and queue them for processing on a separate thread.

1
On

user these links for reference

  1. Validating an email Address in C#

  2. Regex Email validation

there are two option

  1. you can create regex and match the mail address and if it doesn't match then you can throw an excption.

  2. or you can create mailaddress object and put it into try block and use FormatException which is in build in c#