How to send emails in .NET part 9: sending emails
September 5, 2014 Leave a comment
Up to now in this mini series we’ve looked at how to compose email messages. The next step is to actually send them to the recipient(s).
We saw that the easiest way to send a message is using the SmtpClient.Send method:
string from = "andras.nemes@company.com"; string to = "john.smith@company.com"; string subject = "This is the subject"; string plainTextBody = "This is a great message."; MailMessage mailMessage = new MailMessage(from, to, subject, plainTextBody); string smtpServer = "mail.company.com"; SmtpClient client = new SmtpClient(smtpServer); client.Send(mailMessage);
The Send method is a “normal” synchronous method, i.e. it will block the code execution until the email has been sent.
In case you’d like to send the message asynchronously you have at least 2 options. If you have a .NET 4.5 project then you can use the awaitable version of Send, which is SendMailAsync. You don’t know what await-async means? Start here.
The updated code looks like this then:
public async Task SendMessageAsync() { string from = "andras.nemes@company.com"; string to = "john.smith@company.com"; string subject = "This is the subject"; string plainTextBody = "This is a great message."; MailMessage mailMessage = new MailMessage(from, to, subject, plainTextBody); string smtpServer = "mail.company.com"; SmtpClient client = new SmtpClient(smtpServer); await client.SendMailAsync(mailMessage); }
You’d then call the method as follows:
await SendMessageAsync();
Another option is to use the SendAsync method of SmtpClient and hook up to its SendCompleted event:
SmtpClient client = new SmtpClient(smtpServer); client.SendCompleted += client_SendCompleted; client.SendAsync(mailMessage, "Hello world");
…where client_SendCompleted is an event handler:
void client_SendCompleted(object sender, AsyncCompletedEventArgs e) { Console.WriteLine("Cancelled? " + e.Cancelled); Console.WriteLine("Error? " + (e.Error == null)); Console.WriteLine("User specified arg " + (e.UserState == null ? "none" : e.UserState.ToString())); }
…which is called when the sending operation has completed. You can then read if the sending operation has been cancelled, if there are any exceptions and if there are any custom arguments in the UserState object. You can supply your own object here, any object, through the SendAsync method. In the above example I simply put “Hello world” as the custom argument which can be retrieved as e.UserState.ToString().
The sending can be cancelled by the SmtpClient.SendAsyncCancel() method which can be triggered if e.g. the user clicks a button if it takes too long to send the email.
In case your SMTP server supports SSL then make sure you take advantage of it and send the email in an encrypted form:
client.EnableSsl = true;
Read all posts related to emailing in .NET here.