In this article I will explain with an example, how to send email using MailKit library in ASP.Net Core MVC.
Note: For beginners in ASP.Net Core MVC, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Installing MailKit package
You will need to install the MailKit package, for details on installation please refer Install MailKit from Nuget in Visual Studio.
 
 
Mail Server Settings in AppSettings.json file
The mail server settings are saved in the Smtp section as shown below.
{
   "Smtp": {
      "Server": "smtp.gmail.com",
      "Port": 587,
      "CcAddress": "cc@aspsnippets.com",
      "BccAddress": "bcc@aspsnippets.com"
   }
}
 
 
Model
The Model class consists of the following properties.
Note: IFormFile is the new Class for Files in .Net Core. It is a replacement of HttpPostedFileBase class.
 
public class EmailModel
{
    public string To { getset; }
    public string Subject { getset; }
    public string Body { getset; }
    public IFormFile Attachment { getset; }
    public string Email { getset; }
    public string Password { getset; }
}
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using MimeKit;
using MailKit.Net.Smtp;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
 
 
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation
This Action method handles the call made from the POST function from the View.
 
MimeMessage Class Properties
Following are the required properties of the MimeMessage class.
From – Sender’s email address.
To – Recipient(s) Email Address.
CC – Carbon Copies. (If any)
BCC – Blind Carbon Copies. (If any)
Subject – Subject of the Email.
Body – Body of the Email.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
 
SmtpClient Class Methods
Following are the methods of the SmtpClient class.
Connect – The connection to the SMTP Server is established using the domain and the port number.
Authenticate – The username and password of the SMTP Server is authenticated.
Send – The MimeMessage object is passed to it and the email is sent.
Disconnect – Disconnects the connection with SMTP Server.
 
When Send button is clicked, the posted values from their respective fields are captured through the EmailModel class object and are passed as parameter to SendEmail function.
Note: For more details on how to use Model class object for capturing Form field values, please refer my article ASP.Net Core MVC: Form Submit (Post) example.
 
Inside the SendEmail function, Sender email address (from), Recipient email address (to), Subject and Body are fetched from respective TextBoxes and the Cc Address and Bcc Address are fetched from the Smtp section of the AppSettings.json file and are set into an object of the MimeMessage class.
If the IFormFile has attachment then, the attachment is added to the Attachments List of the MimeMessage object.
Finally, an object of the SmtpClient class is created and the Host and Port are fetched from the Smtp section of the AppSettings.json file and are set in Connect method and the methods of the Mail Server such as ConnectAuthenticateSend and Disconnect are executed and a success message is set to a ViewBag object.
public class HomeController : Controller
{
    public IConfiguration Configuration { get; set; }
 
    public HomeController(IConfiguration _configuration)
    {
        Configuration = _configuration;
    }
 
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(EmailModel model)
    {
        this.SendEmail(model.To, model.Email, model.Password, model.Subject, model.Body, model.Attachment);
        ViewBag.Message = "Email Sent.";
        return View();
    }
 
    private void SendEmail(string to, string from, string password, string subject, string body, IFormFile postedFile)
    {
        string host = this.Configuration.GetValue<string>("Smtp:Server");
        int port = this.Configuration.GetValue<int>("Smtp:Port");
        string ccAddress = this.Configuration.GetValue<string>("Smtp:CcAddress");
        string bccAddress = this.Configuration.GetValue<string>("Smtp:BccAddress");
 
        using (MimeMessage mm = new MimeMessage())
        {
            mm.From.Add(new MailboxAddress("Sender", from));
            mm.To.Add(new MailboxAddress("Recipient", to));
            mm.Subject = subject;
            mm.Cc.Add(new MailboxAddress("Cc", ccAddress));
            mm.Bcc.Add(new MailboxAddress("Bcc", bccAddress));
            BodyBuilder builder = new BodyBuilder();
            builder.TextBody = body;
            if (postedFile != null)
            {
                string fileName = Path.GetFileName(postedFile.FileName);
                builder.Attachments.Add(fileName, postedFile.OpenReadStream());
            }
            mm.Body = builder.ToMessageBody();
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Connect(host, port);
                smtp.Authenticate(from, password);
                smtp.Send(mm);
                smtp.Disconnect(true);
            }
        }
    }
}
 
 
View
Inside the View, the EmailModel class is declared as model for the View and ASP.Net TagHelpers in inherited.
The View consists of an HTML Form which has been created using the following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The HTML Form has been specified with enctype=“multipart/form-data” attribute as it is necessary for File Upload operation
Inside the Form there is an HTML Table which consists of some INPUT TextBoxes, in which one TextBox type is set to file.
The Table also consists of an INPUT TextArea and a Submit button.
When the Send Button is clicked, the Form gets submitted and the Model object is sent to the Controller.
Finally, the ViewBag object named Message is checked for NULL and if it is not NULL then the value of the object is displayed using JavaScript Alert Message Box.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Send_Email_MailKit_Core_MVC.Models.EmailModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home" asp-action="Index" enctype="multipart/form-data">
        <table>
            <tr>
                <td style="width: 80px">To:</td>
                <td><input type="text" asp-for="To" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Subject:</td>
                <td><input type="text" asp-for="Subject" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td valign="top">Body:</td>
                <td><textarea cols="20" rows="3" asp-for="Body"></textarea></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>File Attachment:</td>
                <td><input type="file" asp-for="Attachment" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Email:</td>
                <td><input type="text" asp-for="Email" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Password:</td>
                <td><input type="password" asp-for="Password" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Send" /></td>
            </tr>
        </table>
    </form>
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>
 
 
Possible Errors
The possible errors (exceptions) occurring while sending email with MailKit in .Net are covered in the following article.
 
 
Screenshot
Email Form
ASP.Net Core: Send Email using MailKit
 
Received Email
ASP.Net Core: Send Email using MailKit
 
 
Downloads