In this article I will explain a short tutorial with example on how to send emails in ASP.Net MVC Core 2.1.
This article will illustrate how to send emails with attachment using SMTP Mail Server in ASP.Net MVC Core.
This article will make use of GMAIL SMTP Server for sending emails in ASP.Net MVC Core.
Note: For beginners in ASP.Net MVC Core, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Net;
using System.Net.Mail;
 
 
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 { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    public IFormFile Attachment { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}
 
 
Controller
The Controller consists of two 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: This example uses Model class object for capturing Form field values, for more details please refer my article ASP.Net MVC: Form Submit (Post) example.
 
MailMessage Class Properties
Following are the required properties of the MailMessage 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.
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments (if any).
ReplyTo – ReplyTo Email address.
 
SMTP Class Properties
Following are the properties of the SMTP class.
Host – SMTP Server URL (Gmail: smtp.gmail.com).
EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True).
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password).
Port – Port Number of the SMTP server (Gmail: 587).
 
When the Form is submitted, the posted values are captured through the EmailModel class object. All the fetched values are set into an object of the MailMessage class.
If any file is uploaded then it is added as attachment to the Attachments List of the MailMessage Object.
Then an object of the SmtpClient class is created, where the settings of the Mail Server are set. Here Gmail is the Mail Server hence the Mail Settings of the Gmail SMTP Server are used.
Note: It is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be same as the Gmail Username specified in credentials.
Finally if the email is successfully sent, a success message is set to a ViewBag object named Message which will be later displayed on the View.
public class HomeController : Controller
{
    // GET: Home
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(EmailModel model)
    {
        using (MailMessage mm = new MailMessage(model.Email, model.To))
        {
            mm.Subject = model.Subject;
            mm.Body = model.Body;
            if (model.Attachment.Length > 0)
            {
                string fileName = Path.GetFileName(model.Attachment.FileName);
                mm.Attachments.Add(new Attachment(model.Attachment.OpenReadStream(), fileName));
            }
            mm.IsBodyHtml = false;
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host = "smtp.gmail.com";
                smtp.EnableSsl = true;
                NetworkCredential NetworkCred = new NetworkCredential(model.Email, model.Password);
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NetworkCred;
                smtp.Port = 587;
                smtp.Send(mm);
                ViewBag.Message = "Email sent.";
            }
        }
 
        return View();
    }
}
 
 
View
Next step is to add a View for the Controller and while adding you will need to select the EmailModel class created earlier.
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.
ActionNameName 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.
The Form consists of HTML TextBox, TextArea, FileUpload element and a Submit Button.
When the Send Button is clicked, the Form gets submitted and the Model object is sent to the Controller.
@model Send_Email_MVC_Core.Models.EmailModel
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
 
        table th, table td {
            padding: 5px;
        }
    </style>
</head>
<body>
    <div>
        @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>
                <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 type="submit" value="Send"/>
                    </td>
                </tr>
            </table>
            <br/>
            <span style="color:green">@ViewBag.Message</span>
        }
    </div>
</body>
</html>
 
 
Errors while sending Email using Gmail
In case you are getting error from the GMAIL Server, please refer my article GMAIL Error: The SMTP server requires a secure connection or the client was not authenticated.
 
 
Screenshots
The Form
Send Email in ASP.Net MVC Core
 
The received Email
Send Email in ASP.Net MVC Core
 
 
Downloads