How To Send E-mail In ASP.Net Core Using Mailkit

Send E-mail In ASP.Net Core

I am working on this new project where I need to implement a way for us to send newsletters to users on a weekly basis which requires some sort of ways to sending html content in the email.
Well, I’ve always wanted to use this library called Mailkit, so I thought it would be a good opportunity to put a quick post together and sample application to try it first before implementing it in the project. Of course, if you don’t want to use MailKit, you could always make use of the .Net Core SMTP Client.

For simplicity, I’ll keep this post short and focus solely on how to send the e-mail in .NET Core using MailKit.

  • First, create a new ASP.NET Core application with the following name “SendEmailInAspNetCore”
    “File” –>”New” –>”Project”
  • A “New Project” dialog will open. Select “.NET Core” in the left panel inside the Visual C# menu.
    Create send email project to send E-mail In ASP.Net Core
  • Next, select the Web Application (Model-View-Controller) template as shown below.
    Select the right template for the project to send E-mail In ASP.Net Core
  • Once the project is created, make sure to build it and verify that there’s no error before you proceed further.
  • Now, that we know we have a working project to start with, let’s use NuGet to add the “Mailkit” library to the project.
  • Add a new class in the Model folder called “ContactViewModel.cs. In it, we’ll have the following properties to collect the email form data.
    using System.ComponentModel.DataAnnotations;
    
    namespace SendEmailInAspNetCore.Models
    {
        public class ContactViewModel
        {
            [Required]
            [StringLength(60, MinimumLength = 5)]
            public string Name { get; set; }
            [Required]
            [EmailAddress]
            public string Email { get; set; }
            [Required]
            public string Subject { get; set; }
            [Required]
            public string Message { get; set; }
        }
    }
    
    
  • To keep this simple, let’s update the contact view with a simple contact form as shown below.
    
    @model SendEmailInAspNetCore.Models.ContactViewModel
    @{
        ViewData["Title"] = "Contact";
    }
    <h3>Send E-mail In ASP.Net Core 2.1 Using MailKit</h3>
    
    <div class="has-error" col-md-12>
        <form method="post">
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Name">Name:</label>
                    <input asp-for="Name" class="form-control" />
                    <span asp-validation-for="Name" class="text-muted"></span>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Email">Email:</label>
                    <input asp-for="Email" class="form-control" />
                    <span asp-validation-for="Email" class="text-muted"></span>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-4">
                    <label asp-for="Subject">Subject:</label>
                    <input asp-for="Subject" class="form-control" />
                    <span asp-validation-for="Subject" class="text-muted"></span>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-6">
                    <label asp-for="Message">Message:</label>
                    <textarea rows="8" cols="20" asp-for="Message" class="form-control"></textarea>
                    <span asp-validation-for="Message" class="text-muted"></span>
                </div>
            </div>
            <div>
                <button type="submit" class="btn btn-success">Send Message</button>
            </div>
        </form>
    </div>
    
    
  • Let’s update the controller to add a new action to post the contact form to.
     [HttpPost]
     public IActionResult Contact(ContactViewModel contactViewModel)
     {
       if (ModelState.IsValid)
       {
         try
            {
              //instantiate a new MimeMessage
              var message = new MimeMessage();
              //Setting the To e-mail address
              message.To.Add(new MailboxAddress("E-mail Recipient Name", "recipient@domail.com"));
              //Setting the From e-mail address
              message.From.Add(new MailboxAddress("E-mail From Name", "from@domain.com"));
              //E-mail subject 
              message.Subject = contactViewModel.Subject;
              //E-mail message body
              message.Body = new TextPart(TextFormat.Html)
              {
                Text = contactViewModel.Message + " Message was sent by: " + contactViewModel.Name + " E-mail: " + contactViewModel.Email
              };
    
              //Configure the e-mail
              using (var emailClient = new SmtpClient())
              {
                emailClient.Connect("smtp.gmail.com", 587, false);
                emailClient.Authenticate("emailaddress@gmail.com", "password");
                emailClient.Send(message);
                emailClient.Disconnect(true);
               }
            }
            catch (Exception ex)
            {
              ModelState.Clear();
              ViewBag.Message = $" Oops! We have a problem here {ex.Message}";
            }
        }
        return View();
     }
    
  • Let’s run the application now, click on the contact menu item
  • Below is an example error when trying to send the email with a bad credentials.
    Displaying the error message in E-mail In ASP.Net Core
  • Let’s try to send a valid email now. As you can see below the e-mail was received with no problem.
    Showing how message was successfully sent out in the project E-mail In ASP.Net Core

Source Code is available for download on GitHub

Leave Comment

Your email address will not be published. Required fields are marked *