Sending Email Messages with C#

Sending email is quite simple, first we create email message with the help of constructor and then call on SmtpClient method called Send with the message object as its parameter.

MailMessage myMail = new MailMessage
    "My Report.",
    "See the file.");
SmtpClient myClient = new SmtpClient("");

If we want to send email from local IIS based SMTP server we should use SmtpClient.PickupDirectoryLocation property.

Sending mail can be easy but it also requires Exception Handling just like any other code. There are many reasons for exception being thrown. For instance, user account does not exist or SMTP server is not accessible. We need to know how to handle these types of errors. Here is a list that will help us to be prepared for these Exceptions and hopefully to handle them gracefully.


You did not define the server hostname. InvalidOperationException
The server hostname could not be found. SmtpException
Recipient does not have a mailbox. SmtpFailedRecipientException
You are not a valid user. SmtpException

SMTP Servers allow authenticating against it while sending emails via SMTP Server. This is good for many reasons, but primarily it is good to prevent unauthorized access to our SMTP Servers.


SmtpClient myClient = new SmtpClient("");
myClient.Credentials = CredentialCache.DefaultNetworkCredentials;


SmtpClient myClient = new SmtpClient("");
myClient.Credentials = new NetworkCredential("user", "password");

We can also enable SSL for communicating with the SMTP server. Not all SMTP servers support it, but if it does we should always use it.


Sending messages asynchronously is helpful when we want our application to continue working without waiting for the emails to be disseminated. This is handy when SMTP servers are too busy to process email messages right away.

sc = new SmtpClient("server_name");
sc.SendCompleted += new SendCompletedEventHandler(sc_SendCompleted);
sc.SendAsync(mm, null);

void sc_SendCompleted(object sender, AsyncCompletedEventArgs e)
    if (e.Cancelled)
        Console.WriteLine("Message cancelled");
    else if (e.Error != null)
        Console.WriteLine("Error: " + e.Error.ToString());
        Console.WriteLine("Message sent");