In this article I will explain with an example, how to send email with attachment from Folder (Directory) in ASP.Net Core (.Net Core) Razor pages.
Note: For beginners in ASP.Net Core (.Net Core 7) Razor Pages, please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
 

Attachment File location

The File which will be used as Attachment is located inside the Folder (Directory) named Files inside the wwwroot Folder (Directory).
ASP.Net Core Razor Pages: Send Email with attachment from Folder (Directory)
 
 

Mail Server Settings in AppSettings.json file

The following Mail Server settings need to be saved in the AppSettings.json file. 
{
    "Smtp": {
        "Server": "smtp.gmail.com",
        "Port": 587,
        "EnableSsl": true,
        "DefaultCredentials": false
    }
}
 
 

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 { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}
 
 

Namespaces

You will need to import the following namespaces.
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Configuration;
using System.Net.Configuration;
 
 

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 except Attachment.

Setting Body of Email

The Body of the email is Text (Non HTML) hence the IsBodyHtml property of MailMessage class is set to FALSE.

Attaching File

The full path where the file for attachment is located (explained earlier) is fetched using IWebHostEnvironment interface.
Note: The IWebHostEnvironment interface is injected using Dependency Injection inside the Controller, for more details please refer Using IWebHostEnvironment in ASP.Net Core.
          For more details on how to access Static Files in Core, please refer my article Static Files (Images, CSS and JS files) in ASP.Net Core.
 
The BYTE array of that file is fetched using ReadAllBytes method of the File class and added as Attachment to the MailMessage class object.

Sending Email

Then, an object of the SmtpClient class is created and the values of Host, Port, EnableSsl and UseDefaultCredentials are fetched from the SMTP section of the AppSettings.json file and set to the respective properties of SmtpClient class along with the Credentials.
Finally, the Send method is executed which sends the Email and a success message is set to a ViewData object.
public class IndexModel : PageModel
{
    public EmailModel Model { get; set; }
    public IConfiguration Configuration { get; set; }
    private IWebHostEnvironment Environment;
 
    public IndexModel(IConfiguration _configuration, IWebHostEnvironment _environment)
    {
        this.Configuration = _configuration;
        this.Environment = _environment;
    }
 
    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");
        bool enableSsl = this.Configuration.GetValue<bool>("Smtp:EnableSsl");
        bool defaultCredentials = this.Configuration.GetValue<bool>("Smtp:DefaultCredentials");
 
        using (MailMessage mm = new MailMessage(model.Email, model.To))
        {
            mm.Subject = model.Subject;
            mm.Body = model.Body;
            mm.IsBodyHtml = false;
            string filePath = Path.Combine(this.Environment.WebRootPath, "Files/Test.pdf");
            if (System.IO.File.Exists(filePath))
            {
                //Reading file name.
                string fileName = Path.GetFileName(filePath);
                //Reading the file into byte array.
                byte[] bytes = System.IO.File.ReadAllBytes(filePath);
                //Attaching file from Folder/Directory.
                mm.Attachments.Add(new Attachment(new MemoryStream(bytes), fileName));
            }
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host = host;
                smtp.Port = port;
                smtp.EnableSsl = enableSsl;
                smtp.UseDefaultCredentials = defaultCredentials;
                NetworkCredential networkCred = new NetworkCredential(model.Email, model.Password);
                smtp.Credentials = networkCred;
                smtp.Send(mm);
            }
        }
        ViewData["Message"] = "Email sent.";
    }
}
 
 

Razor Page (HTML)

HTML Markup

Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The HTML of Razor Page consists of an HTML Form.
The 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 element 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 ViewData object 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 Send_Email_Single_Attachment_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>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>
 
 

Screenshot

Email Form

ASP.Net Core Razor Pages: Send Email with attachment from Folder (Directory)
 

Received Email

ASP.Net Core Razor Pages: Send Email with attachment from Folder (Directory)
 
 

Downloads