In this article I will explain with an example, how to send email with attachment using MailKit library in ASP.Net MVC.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC 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 Web.Config file
The following Mail Server settings need to be saved in the Web.Config file.
<system.net>
 <mailSettings>
    <smtp deliveryMethod="Network">
      <network
          host="smtp.gmail.com"
          port="587" />
    </smtp>
 </mailSettings>
</system.net>
 
 
MimeKit MimeMessage and MailKit SmtpClient class
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.
 
 
Model
The Model class consists of the following properties.
public class EmailModel
{
    public string To { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    public HttpPostedFileBase Attachment { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }   
}
 
 
Namespaces
You will need to import the following namespaces.
using MimeKit;
using MailKit.Net.Smtp;
using System.IO;
using System.Configuration;
using System.Net.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.
Note: For more details on how to use Model class object for capturing Form field values, please refer my article ASP.Net MVC: Form Submit (Post) example.
 
Inside this Action method, the posted values are captured through the EmailModel class object. All the fetched values are set into an object of the MailMessage class except the Body and Attachment.
Setting Body of Email
For Body and Attachment, an object of Builder class is created. The Body of the email is Text (Non HTML) hence it is set into the TextBody property of the Builder class object.
Attaching File
The HttpPostedFileBase is checked for Attachment and if it has File then the posted File is added as Attachment to the Builder object.
Sending Email
Then, an object of the SmtpClient class is created and the values of Host and Port are fetched from the SMTP section of the Web.Config file and are passed as parameter to the Connect method.
And, the methods of the Mail Server such as Connect, Authenticate, Send and Disconnect are executed and a success message is set to a ViewBag object.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(EmailModel model)
    {       
        //Read SMTP section from Web.Config.
        SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
        string host = smtpSection.Network.Host;
        int port = smtpSection.Network.Port;
 
        using (MimeMessage mm = new MimeMessage())
        {
            mm.From.Add(new MailboxAddress("Sender", model.Email));
            mm.To.Add(new MailboxAddress("Recepient", model.To));
            mm.Subject = model.Subject;
            BodyBuilder builder = new BodyBuilder();
            builder.TextBody = model.Body;

            //Check whether any Attachment is present and attach it.
            if (model.Attachment != null)
            {
                string fileName = Path.GetFileName(model.Attachment.FileName);
                builder.Attachments.Add(fileName, model.Attachment.InputStream);
            }
            mm.Body = builder.ToMessageBody();
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Connect(host, port);
                smtp.Authenticate(model.Email, model.Password);
                smtp.Send(mm);
                smtp.Disconnect(true);
            }
        }
        ViewBag.Message = "Email sent.";
        return View();
    }
}
 
 
View
Inside the View, in the very first line the EmailModel class is declared as model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
HtmlAttributes – This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading Files.
The Form consists of HTML TextBox, TextArea, FileUpload element and a Submit Button.
Note: For more details in creating HTML TextBox, TextArea, FileUpload element in ASP.Net MVC, please refer following articles.
 
When the Submit Button is clicked, the Form gets submitted and the Model object is sent to the Controller.
Note: For more details in Form Submission in ASP.Net MVC, please refer ASP.Net MVC: Form Submit (Post) example.
 
Finally, the ViewBag object is checked for NULL and if it is not NULL then the value of the object is displayed using JavaScript Alert Message Box.
@model SendEmail_Attachment_Mailkit_MVC.Models.EmailModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td style="width: 80px">To:</td>
                <td>@Html.TextBoxFor(model => model.To)</td>
            </tr>
            <tr>
                <td>Subject:</td>
                <td>@Html.TextBoxFor(model => model.Subject)</td>
            </tr>
            <tr>
                <td valign="top">Body:</td>
                <td>@Html.TextAreaFor(model => model.Body, new { rows = "3", cols = "20" })</td>
            </tr>
            <tr>
                <td>File Attachment:</td>
                <td>@Html.TextBoxFor(model => model.Attachment, new { type = "file" })</td>
            </tr>
                <td>Gmail Email:</td>
                <td>@Html.TextBoxFor(model => model.Email)</td>
            </tr>
            <tr>
                <td>Gmail Password:</td>
                <td>@Html.TextBoxFor(model => model.Password, new { type = "password" })</td>
            </tr>
            <tr>
                <td></td>
                <td><input id="btnSend" type="submit" value="Send" /></td>
            </tr>
        </table>
    }
    @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.
 
 
Screenshots
Email Form
Send Email with Attachment using MailKit in ASP.Net MVC
 
Received Email
Send Email with Attachment using MailKit in ASP.Net MVC
 
 
Downloads