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.NETASP.NET CoreExtraction

Mining PDFs with Regex in C#: Practical Patterns, Tips, and Ideas

Mining PDFs with Regex in C# can be a powerful technique for extracting information from documents. This article explores practical patterns, tips, and ideas for effectively using regular…


ASP.NETASP.NET CoreForms

Streamline Data Collection with Embedded Forms in C# .NET

Discover how to enhance your C# .NET applications by embedding forms for data collection. This article explores the benefits of using Text Control's ASP.NET and ASP.NET Core components to create…


ASP.NETASP.NET CorePDF

Adding QR Codes to PDF Documents in C# .NET

This article explains how to add QR codes to PDF documents with the Text Control .NET Server component in C#. It provides the necessary steps and code snippets for effectively implementing this…


ASP.NETASP.NET CorePDF

Adding SVG Graphics to PDF Documents in C# .NET

In this article, we will explore how to add SVG graphics to PDF documents using C# .NET. We will use the TX Text Control .NET Server component to demonstrate the process of rendering SVG images in…


ASP.NETASP.NET CoreKeywords

Enhancing PDF Searchability in Large Repositories by Adding and Reading…

This article explores how to improve the searchability of PDF documents in large repositories by adding and reading keywords with C# .NET. This is especially helpful for applications that manage…