In this article I will explain with an example, how to send email with multiple attachments using Mailkit library in ASP.Net Core Razor Pages.
Note: For beginners in ASP.Net Core Razor, please refer my article ASP.Net Core Razor Pages: 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
  }
}
 
 
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
Following is a Model class named EmailModel with 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 List<IForm> Attachments { getset; }
    public string Email { getset; }
    public string Password { getset; }
}
 
 
Namespaces
You will need to import the following namespaces.
using MimeKit;
using MailKit.Net.Smtp;
using System.IO;
using Microsoft.Extensions.Configuration;
 
 
Razor PageModel (Code-Behind)
The Page Model consists of following Handler methods.
Handler method for handling GET operation
This Handler method left empty, as it is not required.
 
Handler method for handling POST operation
This Handler 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 Core Razor Pages: Form Submit (Post) Example.
 
Inside this Handler 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 Attachments.
Setting Body of Email
For Body and Attachments, 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 multiple Files
The IFormFile is checked for Attachments and if it has Files then a FOR EACH loop is executed over the posted Files and inside the loop each 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 AppSettings.json file and are passed as parameter to the Connect method.
And, the methods of the Mail Server such as ConnectAuthenticateSend and Disconnect are executed and a success message is set into the ViewData object.
public class IndexModel : PageModel
{
    public EmailModel Model { get; set; }
    public IConfiguration Configuration { get; set; }
 
    public IndexModel(IConfiguration _configuration)
    {
        this.Configuration = _configuration;
    }
 
    public void OnGet()
    {
    }
 
    public void OnPostSendEmail(EmailModel model)
    {
        //Read SMTP section from AppSettings.json.
        string host = this.Configuration.GetValue<string>("Smtp:Server");
        int port = this.Configuration.GetValue<int>("Smtp: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;
            if (model.Attachments != null)
            {
                foreach (IFormFile attachment in model.Attachments)
                {
                    string fileName = Path.GetFileName(attachment.FileName);
                    builder.Attachments.Add(fileName, attachment.OpenReadStream());
                }
            }
            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);
            }
        }
        ViewData["Message"] = "Email sent.";
    }
}
 
 
Razor Page (HTML)
Inside the Razor Page, the EmailModel class is declared as model for the View and ASP.Net TagHelpers in inherited.
The HTML of Razor Page consists of an HTML Form.
The HTML Form has been specified with enctype=“multipart/form-data” attribute as it is necessary for File Upload operation
The Form consists of HTML TextBox, TextArea, FileUpload element and a Submit Button.
The FileUpload element has been set with the multiple attribute for selecting multiple Files at a time.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
 
When the Send Button is clicked, the Form gets submitted and the Model object is sent to the PageModel.
@page
@model Multiple_Attachments_MailKit_Core_Razor.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td style="width: 80px">To:</td>
                <td><input type="text" asp-for="Model.To" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Subject:</td>
                <td><input type="text" asp-for="Model.Subject" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td valign="top">Body:</td>
                <td><textarea cols="20" rows="3" asp-for="Model.Body"></textarea></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>File Attachment:</td>
                <td><input type="file" asp-for="Model.Attachments" multiple="multiple" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Email:</td>
                <td><input type="text" asp-for="Model.Email" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Password:</td>
                <td><input type="password" asp-for="Model.Password" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Send" asp-page-handler="SendEmail" /></td>
            </tr>
        </table>
    </form>
    @if (ViewData["Message"] != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewData["Message"]");
            };
        </script>
    }
</body>
</html>
 
 
Possible Errors
The following errors(exceptions) occuring while sending email with Mailkit in .Net are covered in the following article.
 
 
Screenshots
Email Form
Send email with multiple attachments using MailKit in ASP.Net Core Razor Pages
 
Received Email
Send email with multiple attachments using MailKit in ASP.Net Core Razor Pages
 
 
Downloads