.NET, Software Development

Using an Smtp client in ASP.NET MVC 4 and C#

If you need to send emails from your website, the .NET framework provides a very handy library for this:  System.Net.Mail. The configuration and testing is pretty straightforward so let’s get started.

Firstly we need to configure the SMTP settings in the web.config. Under the <configuration> element add the following config section:

The port in the config above may differ from one smtp supplier to another so make sure you follow the appropriate guidelines.

If you only want to test the smtp code without flooding your smtp provider or your mailbox, you can simply redirect all emails to disk. This also allows developers to bypass issues with smtp blocking on different environments and platforms. In the example below I decided to use C:Temp as my email dumping ground but any valid location can be used.

That’s all you need for your smtp settings. Now for the easy part. The code to create and send an email is listed below:

 

In the code above, we create a MailMessage and then pass that message to the smtpClient. I default the message body type to HTML but this can be overwritten by the calling code.

Happy coding…

Standard