MailMessage myMail = new MailMessage
"See the file.");
SmtpClient myClient = new SmtpClient("smtp.email.com");
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("smtp.site.com");
myClient.Credentials = CredentialCache.DefaultNetworkCredentials;
SmtpClient myClient = new SmtpClient("smtp.mail.com");
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);
void sc_SendCompleted(object sender, AsyncCompletedEventArgs e)
else if (e.Error != null)
Console.WriteLine("Error: " + e.Error.ToString());