Skip to main content

Sending Email using .NET



Namespace: System.Net.Mail

How to Send a Message:
SMTPClient class is used to send Mail Messages to users. Mail messages in the pickup directory are automatically sent by a local SMTP server (if present), such as IIS. This property can also be set in a configuration file.

Exception Handling

SMTPException is the root level exception.

SMTPFaildRecipientException: If mail is send to an invalid recipient of the same server that is sending the mail.

InvalidOperationException: Server not defined.

SMTPException (Inner Web Exception) Host not found.

SMPTException: Not a valid user (Credentials) or other transmission problem.

Exceptions and errors are reported through the event Send_Completed in the case one uses SMTPClient.SendAsync to send mail messages.

How to configure credentials:

If one is part of the ISPs SMTP Server on can set credentials using  

           SMTPClient.Credentials = CredentialCache.DefaultNetworkCredentials; 

OR

SMTPClient.Credentials = new NetworkCredentials(“username”,”password”);

It’s recommended to set SMTPClient.EnableSsl to true.

Sending Mail Messages Asynchronously:

By default Application waits for SMTP Server for 100 Seconds, It can be adjusted through SMTPClient.Timeout. On can use SMTPClient.SendAsync(MailMessage, Object) to send mail messages asynchronously. Object is used as parameter for the Send_Completed event, so that one can identify the success or failure of sending to a particular MailAddress.

User can terminate the mail sending process by using SMTPClient.SendAsyncCancel();

Comments