Sending Email Messages with C#
MailMessage myMail = new MailMessage
("name@email.org",
"name2@email2.org",
"My Report.",
"See the file.");
SmtpClient myClient = new SmtpClient("smtp.email.com");
myClient.Send(myMail);
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.
Situation | Exception |
---|---|
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.
Default
SmtpClient myClient = new SmtpClient("smtp.site.com");
myClient.Credentials = CredentialCache.DefaultNetworkCredentials;
Authenticated
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.
SmtpClient.EnableSsl
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);
sc.SendAsyncCancel();
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());
else
Console.WriteLine("Message sent");
}