How to send emails in .NET part 10: handling exceptions

In this mini series on emailing in .NET we saw how to compose and send emails.

There are many things that can go wrong when you send an email: the SMTP server is down, your credentials are invalid, the recipient is invalid etc. When sending an email in .NET you should always catch and handle any SmtpExceptions and SmtpFailedRecipientExceptions. Examples:

SmtpClient client = new SmtpClient(null);
try
{
	client.Send(mailMessage);
}
catch (InvalidOperationException invalid)
{
	Console.WriteLine("Server hostname is missing: " + invalid.Message);
}

InvalidOperationException is thrown in case the host is missing.

string smtpServer = "mail.blahblah.com";
SmtpClient client = new SmtpClient(smtpServer);
try
{
	client.Send(mailMessage);
}
catch (SmtpException smtpNotFound)
{
	Console.WriteLine("Server hostname is invalid: " + smtpNotFound.Message);
}

SmtpClient will try to contact mail.blahblah.com but fails of course. If you run this code then be patient as the default timeout of SmtpClient is 100 seconds, so you won’t see the exception message immediately.

In the above case SmtpException will have an inner exception of type WebException. smtpNotFound.Message like above will only show a generic message: “Failure sending mail”. If you want to dig deeper you’ll need to check if there’s any inner exception:

string smtpServer = "mail.blahblah.com";
SmtpClient client = new SmtpClient(smtpServer);
try
{
	client.Send(mailMessage);
}
catch (SmtpException smtpNotFound)
{
	Console.WriteLine("Server hostname is invalid: " + smtpNotFound.Message);
        if (smtpNotFound.InnerException != null)
	{
		Console.WriteLine(smtpNotFound.InnerException.Message);
	}
}

The inner exception message will be “Unable to connect to the remote server”.

SmtpException can also be thrown if the operation times out, but in that case there will be no inner exceptions:

SmtpClient client = new SmtpClient(smtpServer);
client.Timeout = 10;
try
{
	client.Send(mailMessage);
}
catch (SmtpException smtpNotFound)
{
	Console.WriteLine("Server hostname is invalid: " + smtpNotFound.Message);
}

We set the timeout to 10 seconds which is reached before SmtpClient determines that the SMTP server cannot be reached. Hence the exception message will say “The operation has timed out.”

SmtpException can also be thrown for a variety of other reasons like message transmission problems, so don’t forget to check the inner exception as well, it may contain a more detailed description of the problems.

There’s also an exception of type SmtpFailedRecipientException. If you work at GreatCompany Ltd. and your mail server is mail.greatcompany.com and you want to send an email to john@greatcompany.com then your mail server will be able to determine if the recipient exists and return an error if it doesn’t. If however, you’re sending an email to a recipient on another mail server then mail.greatcompany.com won’t of course see whether the recipient is valid or not. So you can only rely on this exception type if you’re sending an email within your network.

In this post we saw how to send an email asynchronously through SendAsync. The event arguments to the SendCompleted event handler includes a property called Error. If you send your email in this manner than the InvalidOperationException and SmtpException error caught will be set to this property so you can check the result.

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.

2 Responses to How to send emails in .NET part 10: handling exceptions

  1. Brian Christensen says:

    Nice article, just used it.
    I believe that the timeout is in miliseconds and not seconds. It’s a minor thing, but it took me a couple of times to spot that it was miliseconds:
    https://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.timeout(v=vs.110).aspx

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

Elliot Balynn's Blog

A directory of wonderful thoughts

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: