How to send emails in .NET part 9: sending emails

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.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: