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 ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
 
Mail Server Settings in AppSettings.json file
The following Mail Server settings need to be saved in the AppSettings.json file.
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.
 
{
 "Smtp": {
    "Server": "smtp.gmail.com",
    "Port": 587,
    "EnableSsl": true,
    "DefaultCredentials": true,
    "From": "sender@gmail.com",
    "Username": "sender@gmail.com",
    "Password": "GMAILor2STEP-PASSWORD"
 }
}
 
 
Sending Email using Gmail SMTP
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)
 
 
Model
The Model class consists of the following properties.
public class EmailModel
{
    public string To { getset; }
    public string Subject { getset; }
    public string Body { getset; }
}
 
 
Namespaces
You will need to import the following namespaces.
using System.Net;
using System.Net.Mail;
 
 
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
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 object.
Setting Body of Email
The Body of the email is Text (Non HTML) hence the IsBodyHtml property of the MailMessage class object is set to FALSE.
Sending Email
Then, an object of the SmtpClient class is created and the values of Host, Port, DefaultCredentials and EnableSsl are fetched from the SMTP section of the AppSettings.json file and are set in respective properties of the SmtpClient class object.
And Username and Password values are passed as parameter to NetworkCredential class from the SMTP section of the AppSettings.json file.
Finally, the email is being sent using Send method of SmtpClient class object and a success message is set to a ViewData object.
public class IndexModel : PageModel
{
    public IConfiguration Configuration { get; set; }
    public EmailModel Model { get; set; }
 
    public IndexModel(IConfiguration _configuration)
    {
        this.Configuration = _configuration;
    }
 
    public void OnGet()
    {
    }
 
    public void OnPostSendEmail(EmailModel model)
    {
        //Read SMTP section from AppSetting.json.
        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");
        string from = this.Configuration.GetValue<string>("Smtp:From");
        string userName = this.Configuration.GetValue<string>("Smtp:Username");
        string password = this.Configuration.GetValue<string>("Smtp:Password");
 
        using (MailMessage mm = new MailMessage(from, model.To))
        {
            mm.Subject = model.Subject;
            mm.Body = model.Body;
            mm.IsBodyHtml = false;
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host = host;
                smtp.EnableSsl = enableSsl;
                NetworkCredential networkCred = new NetworkCredential(userName, password);
                smtp.UseDefaultCredentials = defaultCredentials;
                smtp.Credentials = networkCred;
                smtp.Port = port;
                smtp.Send(mm);
            }
        }
 
        ViewData["Message"] = "Email sent.";
    }
}
 
 
Razor Page (HTML)
Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The HTML of Razor Page consists of an HTML Form.
The Form consists of HTML TextBox, 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 OnPostSendEmail but here it will be specified as SendEmail 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.
Note: For more details in Form Submission in ASP.Net Core Razor Pages, please refer ASP.Net Core Razor Pages: Form Submit (Post) Example.

Finally, the ViewData 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.
@page
@model Core_Razor_Send_Email.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">
        <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></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 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
 
 
Screenshots
Email Form
ASP.Net Core Razor Pages: Send Email with example
 
Received Email
ASP.Net Core Razor Pages: Send Email with example
 
 
Downloads