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:

<system.net>
  <mailSettings>
    <!-- Method#1: Send emails over the network -->
    <smtp deliveryMethod="Network" from="[email protected]">
      <network host="your_smpt_server_dns_name" userName="your_smpt_server_username"  password="your_smpt_server_password"  port="25" />
    </smtp>  
  </mailSettings>
</system.net>

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.

<system.net>
  <mailSettings>
    <!-- Method#2: Dump emails to a local directory -->
    <smtp deliveryMethod="SpecifiedPickupDirectory" from="[email protected]">
      <network host="localhost" />
      <specifiedPickupDirectory pickupDirectoryLocation="c:temp" />
    </smtp>
  </mailSettings>
</system.net>

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:

public static void SendEmail(string toAddress, string subject, string body, bool isBodyHtml = true)
{
    var mailMessage = new MailMessage();
    mailMessage.To.Add(toAddress);
    mailMessage.Subject = subject;
    mailMessage.Body = body;
    mailMessage.IsBodyHtml = isBodyHtml;

    var smtpClient = new SmtpClient { EnableSsl = false };
    smtpClient.Send(mailMessage);
}

 

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…


  • Share this post on