How to Convert Email to PDF in .NET with C#

Convert Email (.eml) files to PDF with .NET with C# using a multipart pdfRest API request.
Share this page

This .NET walkthrough uses C# and HttpClient to submit the request. It converts an Email (.eml) file into a PDF through the pdfRest Convert to PDF API Tool. The complete sample is included below so .NET with C# developers can see the file handling, request construction, and response path together.

Why Email to PDF in .NET with C#?

.NET services often need to turn communications received by a business workflow into documents that can travel with case records, approval packages, or customer correspondence. An .eml-to-PDF conversion makes that step available directly from C#.

An ASP.NET application handling employee-relations cases could convert a submitted Email file, retain the returned PDF resource ID with the case, and show reviewers a familiar document view alongside the original evidence. The source Email remains a distinct input resource.

The example uses disposable request content and HttpClient, which matches the resource-management model C# developers expect when a service uploads a file and then parses its result.

C# Code Example for Email to PDF

/*
 * What this sample does:
 * - Converts an Email (.eml) file to PDF through the /pdf endpoint.
 * - Sends the Email file directly in a multipart request.
 *
 * Setup (environment):
 * - Set PDFREST_API_KEY=your_api_key_here
 * - Optional: set PDFREST_URL to override the API region.
 *
 * Usage:
 *   dotnet run -- pdf-from-email-multipart 
 */
using System.Net.Http.Headers;

namespace Samples.EndpointExamples.MultipartPayload;

public static class PdfFromEmail
{
    public static async Task Execute(string[] args)
    {
        var inputPath = args.Length > 0 ? args[0] : "/path/to/sample.eml";
        var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
        if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Missing PDFREST_API_KEY");
        var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
        using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
        client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        using var form = new MultipartFormDataContent();
        var inputContent = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath));
        inputContent.Headers.ContentType = new MediaTypeHeaderValue("message/rfc822");
        form.Add(inputContent, "file", Path.GetFileName(inputPath));
        form.Add(new StringContent("pdf_from_email"), "output");
        var response = await client.PostAsync("pdf", form);
        var result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
        if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
    }
}

Source: View the sample on GitHub

Breaking Down the Code

Configure the service and input

var inputPath = args.Length > 0 ? args[0] : "/path/to/sample.eml";
        var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
        if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Missing PDFREST_API_KEY");
        var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";
        using var client = new HttpClient { BaseAddress = new Uri(baseUrl) };
        client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

For this Email to PDF example, .NET with C# sends the multipart request to /pdf. The C# samples use framework HttpClient APIs and disposable content objects. API credentials come from PDFREST_API_KEY, keeping the secret out of the source file and request body. The sample’s placeholder path and API key make the moving pieces visible; replace them with a real local path and protected runtime credential before using the request.

Upload the Email File

using var form = new MultipartFormDataContent();
        var inputContent = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath));
        inputContent.Headers.ContentType = new MediaTypeHeaderValue("message/rfc822");
        form.Add(inputContent, "file", Path.GetFileName(inputPath));
        form.Add(new StringContent("pdf_from_email"), "output");
        var response = await client.PostAsync("pdf", form);
        var result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
        if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
    }
}

The .NET with C# request places the Email source in the multipart part named file. Retain its .eml filename extension because Convert to PDF uses the uploaded name to identify the source type, then use the optional output field to choose the generated resource name without a PDF extension.

Build the multipart request

client.DefaultRequestHeaders.TryAddWithoutValidation("Api-Key", apiKey);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        using var form = new MultipartFormDataContent();
        var inputContent = new ByteArrayContent(await File.ReadAllBytesAsync(inputPath));
        inputContent.Headers.ContentType = new MediaTypeHeaderValue("message/rfc822");
        form.Add(inputContent, "file", Path.GetFileName(inputPath));
        form.Add(new StringContent("pdf_from_email"), "output");
        var response = await client.PostAsync("pdf", form);
        var result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
        if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;

For the Email to PDF form, MultipartFormDataContent owns the uploaded streams and text values. The .NET runtime calculates the multipart boundary and content type when HttpClient sends the container.

Read the output resource

inputContent.Headers.ContentType = new MediaTypeHeaderValue("message/rfc822");
        form.Add(inputContent, "file", Path.GetFileName(inputPath));
        form.Add(new StringContent("pdf_from_email"), "output");
        var response = await client.PostAsync("pdf", form);
        var result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
        if (!response.IsSuccessStatusCode) Environment.ExitCode = 1;
    }
}

After the Email to PDF call, the client reads the response text and reports non-success status through the process exit code. A successful JSON body identifies the managed output resource, while an unsuccessful body should be surfaced to the calling application.

Beyond the Tutorial

In this .NET with C# tutorial, you converted an Email file into a PDF resource with a direct multipart request. The pattern gives a message-based workflow a document output that can be reviewed, downloaded, or passed to another pdfRest operation.

Try representative email to pdf inputs in API Lab. For the authoritative request fields, accepted values, and response contract, consult the Convert to PDF API Tool documentation. The same request pattern can then be adapted to your .NET with C# application’s error handling, retention policy, and delivery workflow.

The repository also provides a JSON-payload Email-to-PDF version for .NET with C#. It uploads the message first and then posts its resource ID to /pdf, which is useful when an application stages inputs for several later operations. View the JSON-payload sample on GitHub.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.