• Home
  • Tutorials
  • Development Tools
  • Contact Us

Developing Software

Mastering Software Craftsmanship

How to Send an E-Mail with ASP.NET Core and Mailgun

15th March 2016 by @developingsoft

Sending Email in ASP.NET MVC used to be easy with the built in SMTP client, but how do you do it in ASP.NET Core?

For some reason there is no built in SMTP client in ASP.NET Core. Which I would of thought would have been an essential part of any web development framework.

There are currently two options that will get you quickly sending emails using ASP.NET Core on the CoreCLI. They are:

  • The third-party MailKit library by Jeffrey Stedfast.
  • or using a Mail delivery service like MailGun to send emails using a REST API.

In this example we will create a simple MailService implementation that uses MailGuns Rest API.

Step 1: Create a Mailgun Account and Verify your Sending Domain

First of all you will need to register for an account at: http://www.mailgun.com. Registration is free and you can send up to 10,000 emails per month.

Once you have created a Mailgun account you will need to add a new domain in the control panel and verify you own the domain name. You must own the domain name and you must verify it by adding some DNS records to your DNS servers. This is pretty straight forward and Mailgun does a good job of showing you step by step instructions on how to do this.

Step 2: Create the MailService class

Create a class named MailService with the following code.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

public class MailService
{
    // the domain name you have verified in your Mailgun account
    const string DOMAIN = "example.com";

    // your API Key used to send mail through the Mailgun API
    const string API_KEY = "key-00000000000000000000000000000000";

    public async Task<bool> SendAsync(string from, string to, string subject, string message)
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes("api" + ":" + API_KEY)));

        var form = new Dictionary<string, string>();
        form["from"] = from;
        form["to"] = to;
        form["subject"] = subject;
        form["text"] = message;

        var response = await client.PostAsync("https://api.mailgun.net/v2/" + DOMAIN + "/messages", new FormUrlEncodedContent(form));

        if (response.StatusCode == HttpStatusCode.OK)
        {
            Debug.WriteLine("Success");
            return true;
        }
        else
        {
            Debug.WriteLine("StatusCode: " + response.StatusCode);
            Debug.WriteLine("ReasonPhrase: " + response.ReasonPhrase);
            return false;
        }
    }
}

As you can see in the code above we are using the HttpClient to send the email using Mailguns API. You will need to add System.Net.Http to your project.json file. The example above uses:

"System.Net.Http": "4.0.1-beta-23516"

Step 3: An Example of Using the MailService

string from = "[email protected]";
string to = "[email protected]";
string subject = "hello world";
string body = "hello world from mailgun";

bool result = await _mailService.SendAsync(from, to, subject, body);

The example above is calling the SendAsync method using the async/await pattern and returns true if the email was accepted by Mailgun.

Thats it.

A very simple way to send email in ASP.NET Core in three easy steps. Obviously you wont be able to use this code if you want to route the mail through your own SMTP server. If that is the case you should check out MailKit instead.

Share this on:

Filed Under: Tutorials Tagged With: ASP.NET Core, C#

Search

Advertisement

Newsletter

Subscribe now to receive practical tips on how to become a better software developer.

Free - No Spam - 100% Email Privacy

Featured Posts

Abstract Factory Pattern: C# Example Using the Unity Game Engine

23 Software Design Patterns That Will Make You a More Effective Programmer

How to Deploy an ASP.NET Core Website to Ubuntu with Git

How to Run an ASP.NET Core Website in Production on Ubuntu Linux

How to Install the Edimax Wireless nano USB Adapter on Windows IoT Core for Raspberry Pi

How to Convert a Post Title into a Friendly URL (Slug) in C#

How to Convert Markdown to HTML in ASP.NET Core

How to Send an E-Mail with ASP.NET Core and Mailgun

How to Generate a Sitemap in ASP.NET MVC and ASP.NET Core

How to Create an MD5 Hash of a String in C# and Displaying a Gravatar Image

© 2014–2023 Developing SoftwareTerms • Privacy