In this article I will explain with an example, how to send email in ASP.Net Core Razor Pages.
Note: For beginners in ASP.Net Core Razor Pages, please refer my article ASP.Net Core Razor Pages: Hello World Tutorial with Sample Program example.
 
 
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,
    "EnableSsl": true,
    "DefaultCredentials": true
 }
}
 
 
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 System.Net;
using System.Net.Mail;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
 
 
Razor PageModel (Code-Behind)
The PageModel 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 Razor Page.
 
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 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 Razor Pages: Form Submit (Post) Example.
 
Inside the SendEmail function, the Sender email address (from), Recipient email address (to), Subject and Body are fetched from respective TextBoxes are set into an object of the MailMessageclass.
If the IFormFile has attachment then, the attachment is added to the Attachments list of the MailMessage object.
Then, an object of the SmtpClient class is created and the values of Host, Port, EnableSsl and DefaultCredentials are fetched from the Smtp section of the AppSettings.json file.
And values of Host and Port are set in the Connect method and the methods of the Mail Server such as ConnectAuthenticateSend and Disconnect are executed and a success message is displayed.
public class IndexModel : PageModel
{
    public string Message { get; set; }
    public IConfiguration Configuration { get; set; }
 
    public IndexModel(IConfiguration _configuration)
    {
        this.Configuration = _configuration;
    }
 
    public void OnGet()
    {
 
    }
 
    public void OnPostSendEmail(EmailModel model)
    {
        this.SendEmail(model.To, model.Email, model.Password, model.Subject, model.Body, model.Attachment);
        this.Message = "Email Sent.";
    }
 
    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");
        bool enableSsl = this.Configuration.GetValue<bool>("Smtp:EnableSsl");
        bool defaultCredentials = this.Configuration.GetValue<bool>("Smtp:DefaultCredentials");
 
        using (MailMessage mm = new MailMessage(from, to))
        {
            mm.Subject = subject;
            mm.Body = body;
            if (postedFile != null)
            {
                string fileName = Path.GetFileName(postedFile.FileName);
                mm.Attachments.Add(new Attachment(postedFile.OpenReadStream(), fileName));
            }
            mm.IsBodyHtml = false;
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host = host;
                smtp.EnableSsl = enableSsl;
                NetworkCredential networkCred = new NetworkCredential(from, password);
                smtp.UseDefaultCredentials = defaultCredentials;
                smtp.Credentials = networkCred;
                smtp.Port = port;
                smtp.Send(mm);
            }
        }
    }
}
 
 
Razor Page (HTML)
Inside the Razor Page, the ASP.Net TagHelpers is 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
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.
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.
Finally, the success message set in the public property named Message is displayed.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Send_Email_Core_Razor.Pages.IndexModel
@{
    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" name="To" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Subject:</td>
                <td><input type="text" name="Subject" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td valign="top">Body:</td>
                <td><textarea cols="20" rows="3" name="Body"></textarea></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>File Attachment:</td>
                <td><input type="file" name="Attachment" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Email:</td>
                <td><input type="text" name="Email" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Password:</td>
                <td><input type="password" name="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>
    <span style="color:green">@Model.Message</span>
</body>
</html>
 
 
Possible Errors
The following error occurs when you try to send email using Gmail credentials in your application.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
 
Solution
 
 
Screenshot
The Form
ASP.Net Core Razor Pages: Send Email
 
The received Email
ASP.Net Core Razor Pages: Send Email
 
 
Downloads