C# & ADO.NET

Files and e-mail in ASP.NET with C#: uploads, previews, extension checks, folder listings, CSV and HTML mail

C# & ADO.NET · · Published 2026-11-29

Files and e-mail are where a web application touches the outside world, and where small mistakes have large consequences: an upload form that accepts scripts, a folder listing that leaks server paths, a mail that breaks in half of the clients. This guide groups the file and mail tasks of a typical Web Forms back office, in the order a user meets them: choosing and previewing a file, having it checked, storing and downloading it, listing what is on disk, exporting that list, and finally sending results by e-mail.

Three rules that apply everywhere

Previewing an image before upload

The first step happens before anything is sent: showing the user the file they picked.

Showing the selected picture before upload lets users catch the wrong file early. The browser can display a local file without sending it anywhere: URL.createObjectURL gives a temporary URL for the file, which an <img> can show immediately.

Plain JavaScript

<asp:FileUpload ID="fuPhoto" runat="server" accept="image/png,image/jpeg,image/webp" />
<img id="preview" alt="Preview of the selected image" hidden style="max-width:240px;max-height:240px">
<p id="photoError" role="alert"></p>

<script>
  (function () {
    var input = document.getElementById("<%= fuPhoto.ClientID %>");
    var img = document.getElementById("preview");
    var error = document.getElementById("photoError");
    var lastUrl = null;

    input.addEventListener("change", function () {
      error.textContent = "";
      if (lastUrl) { URL.revokeObjectURL(lastUrl); lastUrl = null; }
      var file = input.files && input.files[0];
      if (!file) { img.hidden = true; return; }

      if (!/^image\/(png|jpeg|webp)$/.test(file.type)) {
        error.textContent = "Please choose a PNG, JPEG or WebP image.";
        input.value = ""; img.hidden = true; return;
      }
      if (file.size > 5 * 1024 * 1024) {
        error.textContent = "The image must be 5 MB or smaller.";
        input.value = ""; img.hidden = true; return;
      }
      lastUrl = URL.createObjectURL(file);
      img.src = lastUrl;
      img.hidden = false;
    });
  })();
</script>

revokeObjectURL frees the memory held for the previous preview. Clearing input.value removes an invalid file from the form so it is not uploaded.

jQuery version with FileReader

$(function () {
  $("#<%= fuPhoto.ClientID %>").on("change", function () {
    var file = this.files && this.files[0];
    if (!file || file.type.indexOf("image/") !== 0) { $("#preview").prop("hidden", true); return; }
    var reader = new FileReader();
    reader.onload = function (e) {
      $("#preview").attr("src", e.target.result).prop("hidden", false);  // data: URL
    };
    reader.readAsDataURL(file);
  });
});

FileReader.readAsDataURL produces a base64 data: URL. It works everywhere but copies the whole file into a string; createObjectURL is lighter for large photos.

Several images

With AllowMultiple="true" on the FileUpload (.NET 4.5+), loop over input.files and append one <img> per file to a container, applying the same checks to each.

The server still decides

Client checks rely on the browser's reported MIME type, which comes from the file extension. On the server, check the extension against an allow-list, the size, and ideally that the content decodes as an image; store it under a generated name outside the web root. All of this is shown in Upload and download files and Validate the file extension. If the preview is inside an UpdatePanel, make the upload button a PostBackTrigger: files cannot be sent through partial postbacks.

Orientation and privacy

Photos taken with phones may store their rotation in EXIF metadata; current browsers apply it when displaying images, so the preview usually looks right, but server-side processing libraries may not. If you resize images on the server, apply the orientation there too. The same metadata can contain the GPS location where the photo was taken: consider removing EXIF data on the server before publishing user photos.

Checking the file extension in the browser and on the server

Then the type is checked, in four layers from convenience to security.

Restricting uploads to, say, PDF and images starts in the browser, for the user's convenience, and ends on the server, for security. Client checks catch honest mistakes; only the server check can be trusted.

1. Narrow the file picker

<asp:FileUpload ID="fuDoc" runat="server" accept=".pdf,.png,.jpg,.jpeg" />

accept filters what the file dialog shows by default. Users can still switch to "All files".

2. Validator in the page

<asp:RegularExpressionValidator runat="server" ControlToValidate="fuDoc" Display="Dynamic"
    ValidationExpression="^.+\.([pP][dD][fF]|[pP][nN][gG]|[jJ][pP][eE]?[gG])$"
    ErrorMessage="Only PDF, PNG or JPEG files are allowed." />

The validator checks the file name the browser reports. The expression spells out upper and lower case because client-side regular expression validation does not offer a case-insensitive option. On the server, the same validator runs against the posted file name.

3. JavaScript check with a clear message

document.getElementById("<%= fuDoc.ClientID %>").addEventListener("change", function () {
  var allowed = ["pdf", "png", "jpg", "jpeg"];
  var bad = Array.from(this.files).filter(function (f) {
    var ext = f.name.split(".").pop().toLowerCase();
    return allowed.indexOf(ext) < 0 || f.size > 10 * 1024 * 1024;
  });
  if (bad.length) {
    alert("Not accepted: " + bad.map(function (f) { return f.name; }).join(", "));
    this.value = "";   // clear the selection
  }
});

Reading files also gives you the size, which a validator cannot check. The image preview article extends this with a thumbnail: Preview an image before uploading.

4. The server check (required)

private static readonly HashSet<string> Allowed =
    new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".pdf", ".png", ".jpg", ".jpeg" };

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (!IsValid || !fuDoc.HasFile) return;

    string ext = Path.GetExtension(fuDoc.FileName);
    if (!Allowed.Contains(ext) || !SignatureMatches(fuDoc.PostedFile.InputStream, ext))
    {
        lblError.Text = "This file type is not accepted.";
        return;
    }
    // save under a generated name, outside the web root (see the upload article)
}

private static bool SignatureMatches(Stream s, string ext)
{
    var head = new byte[8];
    int n = s.Read(head, 0, head.Length);
    s.Position = 0;   // rewind for saving
    switch (ext.ToLowerInvariant())
    {
        case ".pdf": return n >= 4 && head[0] == 0x25 && head[1] == 0x50 && head[2] == 0x44 && head[3] == 0x46; // %PDF
        case ".png": return n >= 8 && head[0] == 0x89 && head[1] == 0x50 && head[2] == 0x4E && head[3] == 0x47;  // .PNG
        case ".jpg":
        case ".jpeg": return n >= 3 && head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF;
        default: return false;
    }
}

The extension check is an allow-list: anything not listed is refused, including double extensions such as report.pdf.aspx, because Path.GetExtension returns the last one. Checking the first bytes (the file signature) catches files simply renamed to an allowed extension. It does not prove a file is harmless; files served to other users should also be stored safely and, ideally, scanned. The full upload pattern is in Upload and download files.

Uploading to a server folder and downloading again

With the file accepted, it has to be stored safely and served back.

Accepting files from users is one of the riskiest features a web application can have. Done carelessly, an upload form lets anyone place a script on your server and run it. Done properly, it is still short: limit the size, check the type, never trust the client's file name, store files where the web server will not execute them, and serve them back through your own code.

C# code checking the extension, saving under a generated name and streaming the file back with TransmitFile
The upload and download steps in a few lines.

Configuration: size limits

Two settings cap the request size, and the smaller one wins:

<configuration>
  <system.web>
    <!-- kilobytes; default 4096 (4 MB) -->
    <httpRuntime targetFramework="4.8" maxRequestLength="10240" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- bytes; default 30000000 (about 28.6 MB) -->
        <requestLimits maxAllowedContentLength="10485760" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

Exceeding maxRequestLength raises "Maximum request length exceeded"; exceeding IIS's maxAllowedContentLength returns a 404.13 error before ASP.NET even runs. Keep both slightly above the largest file you accept, and check the size in code to give a friendly message.

The page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Files.aspx.cs" Inherits="Demo.Files" %>
<!DOCTYPE html>
<html>
<head runat="server"><title>Files</title></head>
<body>
<form id="form1" runat="server">
    <asp:FileUpload ID="fuFile" runat="server" accept=".pdf,.png,.jpg,.jpeg,.txt" />
    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    <asp:Label ID="lblMessage" runat="server" />

    <asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false" OnRowCommand="gvFiles_RowCommand"
        EmptyDataText="No files uploaded yet.">
        <Columns>
            <asp:BoundField DataField="OriginalName" HeaderText="File" />
            <asp:BoundField DataField="SizeKb" HeaderText="Size (KB)" DataFormatString="{0:N0}" />
            <asp:BoundField DataField="Uploaded" HeaderText="Uploaded (UTC)" DataFormatString="{0:yyyy-MM-dd HH:mm}" />
            <asp:ButtonField CommandName="Download" Text="Download" />
        </Columns>
    </asp:GridView>
</form>
</body>
</html>

The accept attribute filters the browser's file picker. It is a convenience: a user can still pick any file, and a script can post anything. The server makes the real decision.

The code-behind

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class Files : Page
    {
        private const int MaxBytes = 10 * 1024 * 1024;
        private static readonly HashSet<string> Allowed =
            new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".pdf", ".png", ".jpg", ".jpeg", ".txt" };

        // App_Data is never served directly by ASP.NET
        private string StoreDir => Server.MapPath("~/App_Data/uploads");

        protected void Page_Load(object sender, EventArgs e)
        {
            Directory.CreateDirectory(StoreDir);
            if (!IsPostBack) BindFiles();
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (!fuFile.HasFile)
            {
                lblMessage.Text = "Choose a file first.";
                return;
            }

            HttpPostedFile posted = fuFile.PostedFile;
            string originalName = Path.GetFileName(posted.FileName); // older IE sent the full client path
            string ext = Path.GetExtension(originalName);

            if (!Allowed.Contains(ext))
            {
                lblMessage.Text = "Only PDF, PNG, JPEG and text files are accepted.";
                return;
            }
            if (posted.ContentLength == 0 || posted.ContentLength > MaxBytes)
            {
                lblMessage.Text = "Files must be between 1 byte and 10 MB.";
                return;
            }

            // Never use the client's name on disk: generate one, keep the original as metadata.
            string storedName = Guid.NewGuid().ToString("N") + ext.ToLowerInvariant();
            posted.SaveAs(Path.Combine(StoreDir, storedName));
            File.WriteAllText(Path.Combine(StoreDir, storedName + ".name"), originalName);

            lblMessage.Text = "Uploaded " + Server.HtmlEncode(originalName) + ".";
            BindFiles();
        }

        private void BindFiles()
        {
            var files = new DirectoryInfo(StoreDir).GetFiles()
                .Where(f => Allowed.Contains(f.Extension))
                .OrderByDescending(f => f.CreationTimeUtc)
                .Select(f => new
                {
                    Stored = f.Name,
                    OriginalName = ReadOriginalName(f),
                    SizeKb = Math.Max(1, f.Length / 1024),
                    Uploaded = f.CreationTimeUtc
                })
                .ToList();

            gvFiles.DataKeyNames = new[] { "Stored" };
            gvFiles.DataSource = files;
            gvFiles.DataBind();
        }

        private static string ReadOriginalName(FileInfo f)
        {
            string meta = f.FullName + ".name";
            return File.Exists(meta) ? File.ReadAllText(meta) : f.Name;
        }

        protected void gvFiles_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName != "Download") return;

            int index = Convert.ToInt32(e.CommandArgument);
            string stored = (string)gvFiles.DataKeys[index].Value;

            // The key comes back from view state, but validate it anyway.
            if (stored.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || !Allowed.Contains(Path.GetExtension(stored)))
                return;

            string fullPath = Path.Combine(StoreDir, stored);
            if (!File.Exists(fullPath)) return;

            string downloadName = ReadOriginalName(new FileInfo(fullPath));
            Response.Clear();
            Response.ContentType = MimeMapping.GetMimeMapping(downloadName);
            Response.AddHeader("Content-Disposition",
                "attachment; filename*=UTF-8''" + Uri.EscapeDataString(downloadName));
            Response.AddHeader("X-Content-Type-Options", "nosniff");
            Response.TransmitFile(fullPath);
            Response.Flush();
            Response.SuppressContent = true;
            Context.ApplicationInstance.CompleteRequest();
        }
    }
}

Why each precaution matters

Checking the extension does not prove the content. If you accept images, you can additionally decode them (for example with System.Drawing.Image.FromStream inside a try/catch, or a maintained imaging library) and reject files that are not valid images. For files other people will download, consider antivirus scanning on the server.

Several files at once

Since .NET 4.5, FileUpload supports multiple selection:

<asp:FileUpload ID="fuFiles" runat="server" AllowMultiple="true" />
foreach (HttpPostedFile file in fuFiles.PostedFiles)
{
    // apply the same checks to each file
}

Remember that maxRequestLength applies to the whole request, so the total of all files must fit.

UpdatePanel and uploads

A FileUpload does not work inside an asynchronous postback: the browser cannot send files through the partial-page request that UpdatePanel uses. Register the upload button as a PostBackTrigger so it performs a full postback.

Related

Listing all files in a folder and its subfolders

Stored files eventually need to be listed: for an admin page, a clean-up job or an inventory.

.NET can list every file below a folder in one call. The choices are between getting an array at once (GetFiles) or streaming results (EnumerateFiles), and deciding what to do with folders you are not allowed to read.

One line

using System.IO;

string[] all = Directory.GetFiles(@"C:\Data\Reports", "*.*", SearchOption.AllDirectories);
string[] pdfs = Directory.GetFiles(@"C:\Data\Reports", "*.pdf", SearchOption.AllDirectories);

GetFiles builds the whole array before returning. EnumerateFiles returns results as it finds them, so you can start processing immediately and stop early:

foreach (string path in Directory.EnumerateFiles(root, "*.log", SearchOption.AllDirectories))
{
    if (new FileInfo(path).Length > 100_000_000) { Console.WriteLine("Large: " + path); }
}

Access denied in one subfolder

With SearchOption.AllDirectories on .NET Framework, a single unreadable subfolder throws UnauthorizedAccessException and you lose the whole result. Walk the tree yourself and skip what you cannot read:

public static IEnumerable<string> SafeEnumerateFiles(string root, string pattern)
{
    var pending = new Stack<string>();
    pending.Push(root);
    while (pending.Count > 0)
    {
        string dir = pending.Pop();
        string[] files = Array.Empty<string>(), subdirs = Array.Empty<string>();
        try
        {
            files = Directory.GetFiles(dir, pattern);
            subdirs = Directory.GetDirectories(dir);
        }
        catch (UnauthorizedAccessException) { }
        catch (DirectoryNotFoundException) { }

        foreach (string f in files) yield return f;
        foreach (string d in subdirs) pending.Push(d);
    }
}

On .NET Core 2.1 and later (including .NET 8), EnumerationOptions does this for you: new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true }.

Pattern quirks

Showing the files on a Web Forms page

string root = Server.MapPath("~/App_Data/reports");
var rows = SafeEnumerateFiles(root, "*")
    .Select(p => new FileInfo(p))
    .Select(f => new
    {
        Folder = f.DirectoryName.Substring(root.Length).TrimStart('\\'),
        f.Name,
        SizeKb = Math.Ceiling(f.Length / 1024.0),
        Modified = f.LastWriteTime
    })
    .OrderBy(x => x.Folder).ThenBy(x => x.Name)
    .ToList();
gvFiles.DataSource = rows;
gvFiles.DataBind();

Only list folders the application owns, never a path taken from user input; and the application pool identity needs read permission on them. Exporting such a list to CSV or Excel: Export a folder's file list.

Performance notes

Enumerating a large network share can take minutes. Avoid doing it inside a web request: run it in a scheduled job, store the result (for example in a table), and let the page read that. When you must enumerate on demand, use EnumerateFiles, stop as soon as you have what you need, and avoid calling new FileInfo(path) for every file unless you need sizes or dates; DirectoryInfo.EnumerateFiles returns FileInfo objects whose basic properties come from the directory listing itself.

Exporting a file list to CSV or Excel

An inventory is most useful in a spreadsheet.

An inventory of files, with names, sizes and dates, is a common request from people who want to sort and filter it in Excel. DirectoryInfo gives you the data; writing a CSV that Excel opens without mangling accents or dates takes a few precautions.

Collect the data

using System.IO;
using System.Linq;

var root = new DirectoryInfo(@"D:\Shared\Projects");
var files = root.EnumerateFiles("*", SearchOption.AllDirectories)
    .Select(f => new
    {
        Folder = Path.GetRelativePath(root.FullName, f.DirectoryName), // .NET Core 2.0+; see note
        f.Name,
        f.Extension,
        f.Length,
        f.LastWriteTimeUtc
    })
    .ToList();

Path.GetRelativePath does not exist on .NET Framework; there, use f.DirectoryName.Substring(root.FullName.Length).TrimStart('\\'). If some subfolders are unreadable, use the safe enumeration shown in List files recursively.

Write CSV

using System.Globalization;
using System.Text;

static string Q(string s) =>
    s.IndexOfAny(new[] { ',', '"', '\r', '\n' }) >= 0 ? "\"" + s.Replace("\"", "\"\"") + "\"" : s;

var sb = new StringBuilder();
sb.AppendLine("Folder,Name,Extension,SizeBytes,ModifiedUtc");
foreach (var f in files)
{
    sb.Append(Q(f.Folder)).Append(',')
      .Append(Q(f.Name)).Append(',')
      .Append(Q(f.Extension)).Append(',')
      .Append(f.Length.ToString(CultureInfo.InvariantCulture)).Append(',')
      .AppendLine(f.LastWriteTimeUtc.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
}
File.WriteAllText(@"D:\Exports\files.csv", sb.ToString(), new UTF8Encoding(true)); // with BOM

Write a real .xlsx

To avoid separator and encoding questions entirely, create a workbook with ClosedXML (see Export GridView data to Excel for setup):

using ClosedXML.Excel;

using (var wb = new XLWorkbook())
{
    var ws = wb.Worksheets.Add("Files");
    ws.Cell(1, 1).InsertTable(files);   // header row from property names, formatted as a table
    ws.Columns().AdjustToContents();
    wb.SaveAs(@"D:\Exports\files.xlsx");
}

Sizes stay numeric and dates stay dates, so users can sort and sum them immediately.

From an ASP.NET page

Instead of saving to disk, send the bytes as a download with Content-Disposition: attachment, as in the GridView export article. Only list folders the application controls, and remember the application pool identity needs read access to them.

Large folders

For hundreds of thousands of files, building the whole CSV in a StringBuilder uses a lot of memory. Write directly to a StreamWriter created with new StreamWriter(path, false, new UTF8Encoding(true)) and write one line per file as you enumerate. The output is identical and memory use stays flat.

Sending an HTML template as an e-mail

The other way out of the application is e-mail, starting with templated HTML messages.

An order confirmation or a newsletter is an HTML document sent as the body of an e-mail. The robust approach is a template file with placeholders, filled in code, sent with both an HTML and a plain-text version. Grabbing a live page's HTML with a web request looks tempting but brings scripts, external CSS and authentication problems with it.

The template

Save ~/App_Data/Templates/OrderConfirmation.html with inline styles (e-mail clients ignore most <style> blocks and external stylesheets):

<!DOCTYPE html>
<html lang="en">
<body style="margin:0;padding:0;background:#f4f4f4">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f4"><tr><td align="center">
    <table width="600" cellpadding="24" cellspacing="0" style="background:#ffffff;font-family:Arial,sans-serif;font-size:15px;color:#222222">
      <tr><td>
        <img src="cid:logo" alt="Example Shop" width="140" height="40">
        <h1 style="font-size:22px">Thank you, {{Name}}</h1>
        <p>Your order <strong>#{{OrderId}}</strong> of {{Total}} has been received.</p>
        <p><a href="{{OrderUrl}}" style="color:#0e6a70">View your order</a></p>
      </td></tr>
    </table>
  </td></tr></table>
</body>
</html>

Filling and sending

public static void SendOrderConfirmation(Order o, string customerEmail)
{
    string path = HostingEnvironment.MapPath("~/App_Data/Templates/OrderConfirmation.html");
    string html = File.ReadAllText(path)
        .Replace("{{Name}}", HttpUtility.HtmlEncode(o.CustomerName))
        .Replace("{{OrderId}}", o.Id.ToString())
        .Replace("{{Total}}", HttpUtility.HtmlEncode(o.Total.ToString("C", CultureInfo.GetCultureInfo("en-IE"))))
        .Replace("{{OrderUrl}}", HttpUtility.HtmlAttributeEncode("https://www.example.com/orders/" + o.Id));

    string text = $"Thank you, {o.CustomerName}.\r\nYour order #{o.Id} has been received.\r\nhttps://www.example.com/orders/{o.Id}";

    using (var msg = new MailMessage())
    using (var smtp = new SmtpClient())
    {
        msg.To.Add(customerEmail);
        msg.Subject = $"Order #{o.Id} confirmed";

        // plain text first, HTML last: clients pick the last part they can display
        msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, Encoding.UTF8, "text/plain"));
        var htmlView = AlternateView.CreateAlternateViewFromString(html, Encoding.UTF8, "text/html");

        // embedded logo referenced as cid:logo
        var logo = new LinkedResource(HostingEnvironment.MapPath("~/App_Data/Templates/logo.png"), "image/png")
        {
            ContentId = "logo"
        };
        htmlView.LinkedResources.Add(logo);
        msg.AlternateViews.Add(htmlView);

        smtp.Send(msg);
    }
}

Each value is HTML-encoded before insertion, so a customer named <b>Ann</b> cannot inject markup into the message. Embedded images (cid:) display without the recipient allowing remote images; linking to images on your server is the alternative, at the cost of being blocked by default in many clients.

Why not send a live .aspx page?

Downloading your own page with WebClient.DownloadString and mailing the result means a second HTTP request (without the user's login cookie), relative links that break outside the site, scripts that e-mail clients strip, and stylesheets they ignore. Rendering a user control to a string is possible but carries the same CSS issues. A dedicated template is predictable and testable.

Sending tabular data is covered in Send a GridView by e-mail; SMTP settings in Sending test mail through Gmail SMTP.

Testing the result

E-mail clients differ far more than browsers. Before sending to customers, send test messages to accounts in the main webmail services and desktop clients your audience uses, check the plain-text version, and look at the message with images blocked. Keep the template narrow (about 600 pixels), use tables for layout, and avoid background images and web fonts that many clients ignore.

Sending GridView rows by e-mail

A common variant is "mail me this list": the body is built from the grid's data.

"E-mail me this list" turns a GridView into the body of an HTML message. Old tutorials render the grid control itself into a string; building the table from the data is cleaner, survives e-mail clients' limited CSS, and makes it easy to send only the rows the user selected.

Build the HTML from the data

private static string ToHtmlTable(IEnumerable<OrderRow> rows)
{
    var sb = new StringBuilder();
    sb.Append("<table cellpadding=\"6\" cellspacing=\"0\" style=\"border-collapse:collapse;font-family:Arial,sans-serif;font-size:14px\">");
    sb.Append("<tr style=\"background:#0e6a70;color:#ffffff\"><th align=\"left\">Order</th><th align=\"left\">Customer</th><th align=\"right\">Total</th></tr>");
    foreach (var r in rows)
    {
        sb.Append("<tr style=\"border-bottom:1px solid #dddddd\">")
          .Append("<td>").Append(r.OrderId).Append("</td>")
          .Append("<td>").Append(HttpUtility.HtmlEncode(r.Customer)).Append("</td>")
          .Append("<td align=\"right\">").Append(r.Total.ToString("N2", CultureInfo.GetCultureInfo("en-GB"))).Append("</td>")
          .Append("</tr>");
    }
    sb.Append("</table>");
    return sb.ToString();
}

E-mail clients ignore most stylesheets, so styles are inline and the table uses old-fashioned attributes such as cellpadding that every client understands. Text from the database is HTML-encoded.

All rows or only the ticked ones

<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" DataKeyNames="OrderId">
    <Columns>
        <asp:TemplateField><ItemTemplate><asp:CheckBox ID="chkSend" runat="server" /></ItemTemplate></asp:TemplateField>
        <asp:BoundField DataField="OrderId" HeaderText="Order" />
        <asp:BoundField DataField="Customer" HeaderText="Customer" />
        <asp:BoundField DataField="Total" HeaderText="Total" DataFormatString="{0:N2}" />
    </Columns>
</asp:GridView>
<asp:TextBox ID="txtTo" runat="server" TextMode="Email" />
<asp:Button ID="btnSendAll" runat="server" Text="E-mail all" OnClick="btnSend_Click" CommandArgument="all" />
<asp:Button ID="btnSendSelected" runat="server" Text="E-mail selected" OnClick="btnSend_Click" CommandArgument="selected" />
protected void btnSend_Click(object sender, EventArgs e)
{
    bool onlySelected = ((Button)sender).CommandArgument == "selected";
    var ids = new HashSet<int>();
    foreach (GridViewRow row in gvOrders.Rows)
    {
        if (!onlySelected || ((CheckBox)row.FindControl("chkSend")).Checked)
            ids.Add((int)gvOrders.DataKeys[row.RowIndex].Value);
    }
    if (ids.Count == 0) { lblResult.Text = "No rows selected."; return; }

    // Re-read from the database: never trust values shown in the page
    List<OrderRow> rows = OrderRepository.GetByIds(ids);

    using (var msg = new MailMessage())
    using (var smtp = new SmtpClient())   // settings from <system.net><mailSettings>
    {
        msg.To.Add(new MailAddress(txtTo.Text.Trim()));
        msg.Subject = $"Orders ({rows.Count})";
        msg.IsBodyHtml = true;
        msg.Body = "<p>Here are the requested orders:</p>" + ToHtmlTable(rows);
        smtp.Send(msg);
    }
    lblResult.Text = "Sent.";
}

With paging, gvOrders.Rows only contains the current page; "all" then means "this page". To send everything, query the whole result instead of reading ids from the grid, and combine with keeping selections across pages.

Validate the recipient, or better, send only to the signed-in user's own address: a form that mails arbitrary content to arbitrary addresses is an open relay for spammers.

RenderControl, if you must

Rendering the GridView itself with gvOrders.RenderControl(htmlTextWriter) also works but requires overriding VerifyRenderingInServerForm, includes check boxes and links that make no sense in an e-mail, and depends on CSS classes the e-mail client will not have. The technique is shown in Export GridView data. SMTP configuration: Sending test mail through Gmail SMTP.

Configuring the SMTP side, including Gmail's requirements, is covered in sending a test mail with Gmail SMTP settings.

Checklist

Sources