In this article I will explain with an example, how to implement Contact Us Form in ASP.Net Core Razor Pages.
The Contact Us Form consists of TextBox controls, a Rich TextBox and a FileUpload control to attach file.
When the Send Button is clicked, the values from the TextBox fields are embedded into HTML string and the HTML string is send as Email along with the Attachment 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.
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Net;
using System.Net.Mail;
using Microsoft.Extensions.Configuration;
 
 
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 ContactFormModel
{
    public string Name { get; set; }
    public string Subject { get; set; }
    public string Email { get; set; }
    public string Body { get; set; }
    public IFormFile Attachment { get; set; }
}
 
 
Mail Server Settings in AppSettings.json file
The mail server settings are saved in the Smtp section as shown below.
{
 "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
 },
 "Smtp": {
    "Server": "smtp.gmail.com",
    "Port": 587,
    "FromAddress": "sender@gmail.com",
    "UserName": "sender@gmail.com",
    "Password": "GMAILor2STEP-PASSWORD"
 }
}
 
 
Razor PageModel (Code-Behind)
The PageModel consists of the following two Handler methods.
Handler method for handling GET operation
This Handler method is 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 Page.
Note: This example uses Model class object for capturing Form field values, for more details please refer my article ASP.Net Core Razor Pages: 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).
Note: The mail server settings will be read from AppSettings.json, for more details please refer Read Email Settings from AppSettings.json in ASP.Net Core.
 
When the Form is submitted, the posted values are captured through the ContactFormModel class object.
The Sender email address (from) is fetched from the Smtp section of the AppSettings.json file, the Subject and Body are fetched from their respective Model properties.
If a file is attached then it is added as attachment to the Attachments List of the MailMessage object and all these values are set into an object of the MailMessage class.
Note: For details about uploading Files in ASP.Net Core Razor Pages, please refer Upload File in ASP.Net Core Razor Pages.
 
Finally, object of the SmtpClient class is created and the settings of the Mail Server such as Host, Port, Username and Password are fetched from the Smtp section of the AppSettings.json file and are set in respective properties of the SmtpClient class object.
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, a success message is set to the Message property which will be later displayed on the Page.
public class IndexModel : PageModel
{
    public string Message { get; set; }
 
    private IConfiguration Configuration;
    public IndexModel(IConfiguration _configuration)
    {
        Configuration = _configuration;
    }
 
    public void OnGet()
    {
 
    }
 
    public void OnPostSubmit(ContactFormModel model)
    {
        //Read SMTP settings from AppSettings.json.
        string host = this.Configuration.GetValue<string>("Smtp:Server");
        int port = this.Configuration.GetValue<int>("Smtp:Port");
        string fromAddress = this.Configuration.GetValue<string>("Smtp:FromAddress");
        string userName = this.Configuration.GetValue<string>("Smtp:UserName");
        string password = this.Configuration.GetValue<string>("Smtp:Password");
 
        using (MailMessage mm = new MailMessage(fromAddress, "admin@aspsnippets.com"))
        {
            mm.Subject = model.Subject;
            mm.Body = "Name: " + model.Name + "<br /><br />Email: " + model.Email + "<br />" + model.Body;
            mm.IsBodyHtml = true;
 
            if (model.Attachment.Length > 0)
            {
                string fileName = Path.GetFileName(model.Attachment.FileName);
                mm.Attachments.Add(new Attachment(model.Attachment.OpenReadStream(), fileName));
            }
 
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host = host;
                smtp.EnableSsl = true;
                NetworkCredential NetworkCred = new NetworkCredential(userName, password);
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NetworkCred;
                smtp.Port = port;
                smtp.Send(mm);
                this.Message = "Email sent sucessfully.";
            }
        }
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page consists of an HTML Form consisting of HTML TextBox, TextArea, FileUpload element and a Submit Button.
The Body TextArea (Multiline TextBox) is made a Rich TextBox using the TinyMCE RichTextEditor plugin.
Note: For more details, please refer my article ASP.Net Core Razor Pages: TinyMCE RichTextBox (RichTextEditor).
 
The HTML Form has been specified with enctype=“multipart/form-data” attribute as it is necessary for File Upload operation and the FileUpload element has been specified with an additional HTML5 attribute multiple = “multiple” to allow user to select multiple files.
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 Email is sent.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model ContactForm_Email_Razor_Core.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 border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td style="width: 80px">Name:</td>
                <td><input type="text" name="Name"/></td>
            </tr>
            <tr>
                <td>Subject:</td>
                <td><input type="text" name="Subject"/></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input type="text" name="Email"/></td>
            </tr>
            <tr>
                <td valign="top">Body:</td>
                <td><textarea cols="20" rows="10" name="Body"></textarea></td>
            </tr>
            <tr>
                <td>Attachment:</td>
                <td><input type="file" name="Attachment"/></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Send" asp-page-handler="Submit"/></td>
            </tr>
        </table>
        <br/>
        <span style="color:green">@Model.Message</span>
    </form>
 
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.0.20/tinymce.min.js"></script>
    <script type="text/javascript">
        tinymce.init({ selector: 'textarea', width: 300 });
    </script>
</body>
</html>
 
 
Errors while sending Email using Gmail
The following error occurs when you try to send email using Gmail credentials in your ASP.Net MVC 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
The Contact Us Form
ASP.Net Core Razor Pages: Contact Us Form
 
The received email
ASP.Net Core Razor Pages: Contact Us Form
 
 
Downloads