Products Technologies Demo Docs Blog Support Company

Create and Send PDF Documents as Email Attachments with .NET C#

This article shows how to create a PDF document and send it as an email attachment using .NET C#. The PDF is created using the TX Text Control .NET Server component and the email is sent using the System.Net.Mail namespace.

Create and Send PDF Documents as Email Attachments with .NET C#

Sending PDF documents attached to emails is a common and critical task for developers. PDF is the gold standard for document exchange, offering consistent formatting and cross-platform compatibility, making it ideal for sharing invoices, reports, contracts, and other business-critical information. From a developer's perspective, automating the creation and delivery of these documents streamlines workflows, increases efficiency, and ensures reliable communication.

For example, a Web application can automatically generate and email a personalized invoice to a customer immediately after a purchase. In this article, we will explore how to create the PDF document and send it as an attachment to an email.

Creating the Application

To demonstrate how easy this is with the TX Text Control library, we will use a .NET console application.

Make sure that you downloaded the latest version of Visual Studio 2022 that comes with the .NET 8 SDK.

Prerequisites

The following tutorial requires a trial version of TX Text Control .NET Server.

  1. In Visual Studio 2022, create a new project by choosing Create a new project.

  2. Select Console App as the project template and confirm with Next.

  3. Choose a name for your project and confirm with Next.

  4. In the next dialog, choose .NET 8 (Long-term support) as the Framework and confirm with Create.

Adding the NuGet Package

  1. In the Solution Explorer, select your created project and choose Manage NuGet Packages... from the Project main menu.

    Select Text Control Offline Packages from the Package source drop-down.

    Install the latest versions of the following package:

    • TXTextControl.TextControl.ASP.SDK

    ASP.NET Core Web Application

Implementing an Email Class

Before we start creating the PDF document, we need to implement a class that sends an email with an attachment. This class will be used to send the generated PDF document as an attachment.

Create a new class file in your project and name it SmtpMail.cs. Add the following code:

using System.Net.Mail;

public static class SmtpMail
{
    /// <summary>
    /// Sends an email with the specified recipient, subject, body, and attachment.
    /// </summary>
    /// <param name="recipient">The recipient's email address.</param>
    /// <param name="subject">The subject of the email.</param>
    /// <param name="body">The body content of the email.</param>
    /// <param name="attachment">The email attachment.</param>
    public static void Send(string recipient, string subject, string body, Attachment attachment)
    {
        // Create a new email message with sender and recipient details.
        MailMessage emailMessage = new MailMessage("sender@yourdomain.com", recipient)
        {
            Subject = subject,            // Set the email subject.
            IsBodyHtml = false,           // Specify that the body is plain text (not HTML).
            Body = body                   // Set the email body content.
        };

        // Add the specified attachment to the email.
        emailMessage.Attachments.Add(attachment);

        // Configure and send the email using an SMTP client.
        using (SmtpClient client = new SmtpClient())
        {
            client.Host = "smtp.yourprovider.com";                              
            client.UseDefaultCredentials = false;                              
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;           
            client.Credentials = new System.Net.NetworkCredential("username", "password"); 
            client.Port = 587;                                                 
            client.EnableSsl = true;                                           

            // Send the email.
            client.Send(emailMessage);
        }
    }
}

Creating the PDF Document

Now, we can create the PDF document using TX Text Control. Add the following code to the Program.cs file:

using System.Net.Mail;

// Create an instance of the ServerTextControl class for server-side document processing.
using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl())
{
    // Initialize the ServerTextControl instance.
    tx.Create();

    // Set the text content for the document.
    tx.Text = "Hello, this is a PDF document.";

    // Declare a byte array to hold the generated PDF data.
    byte[] pdfAttachment;

    // Save the document content as a PDF into the byte array.
    tx.Save(out pdfAttachment, TXTextControl.BinaryStreamType.AdobePDF);

    // Create an email attachment from the PDF byte array.
    Attachment attachment = new Attachment(
        new MemoryStream(pdfAttachment), // Stream containing the PDF data.
        "document.pdf",                  // Filename for the attachment.
        "application/pdf"                // MIME type for a PDF file.
    );

    // Send an email with the attachment.
    SmtpMail.Send(
        "recipient@domain.com",  // Recipient email address.
        "Subject",                 // Email subject.
        "Body",                    // Email body.
        attachment                 // Attachment to include in the email.
    );
}

This code creates a new instance of the ServerTextControl class and creates a simple text. The document is then exported to a PDF file using the Save method.

The exported byte array is used to create an email attachment from a MemoryStream, which is then passed to the Send method of our implemented SmtpMail class. The following screenshot shows the email with the PDF document attached:

Email with PDF attachment

Conclusion

Creating PDF documents and sending them as email attachments is a common task for developers. With TX Text Control, this task is easy and can be implemented in just a few lines of code. The TX Text Control library provides a powerful API for creating, modifying and exporting documents to various formats, including PDF.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETAIASP.NET Core

Automating PDF/UA Accessibility with AI: Describing DOCX Documents Using TX…

This article shows how to use TX Text Control together with the OpenAI API to automatically add descriptive texts (alt text and labels) to images, links, and tables in a DOCX. The resulting…


ASP.NETASP.NET CoreJava

Converting Office Open XML (DOCX) to PDF in Java

Learn how to convert Office Open XML (DOCX) documents to PDF in Java using the powerful ServerTextControl library. This guide provides step-by-step instructions and code examples to help you…


ASP.NETASP.NET CoreDS Server

Extending DS Server with Custom Digital Signature APIs

In this article, we will explore how to extend the functionality of DS Server by integrating custom digital signature APIs. We will cover the necessary steps to create a plugin that allows DS…


ASP.NETASP.NET CorePDF

Why PDF/UA and PDF/A-3a Matter: Accessibility, Archiving, and Legal Compliance

It is more important than ever to ensure that documents are accessible, archivable, and legally compliant. PDF/UA and PDF/A-3a are two effective standards for addressing these needs. This article…


ASP.NETASP.NET CoreMarkdown

Convert Markdown to PDF in a Console Application on Linux and Windows

Learn how to convert Markdown files to PDF in a console application on Linux and Windows using TX Text Control .NET Server for ASP.NET. This tutorial provides step-by-step instructions and code…