> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pdf.co/llms.txt
> Use this file to discover all available pages before exploring further.

# PDF from Email

> Convert email files (`.msg` or `.eml`) code into PDF. Extract attachments (if any) from input email and embeds into PDF as PDF attachments.

<Note>
  **Try it live:** [PDF from Email → API Tester](/api-tester/pdf-from-email) — send a real request from your browser.
</Note>

## `POST /v1/pdf/convert/from/email`

<Note>
  Images and attachments within `.eml` and `.msg` files **must be publicly accessible.** Resources stored on local file systems or gated behind authentication are not supported for processing.
</Note>

## Attributes

<Note>Attributes are case-sensitive and should be inside JSON for POST request. for example: `{ "url": "https://example.com/file1.pdf" }`</Note>

| Attribute                                                 | Type    | Required | Default    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| --------------------------------------------------------- | ------- | -------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `url`                                                     | string  | *Yes*    | -          | URL to the source file [`url` attribute](/api-reference/url-input-and-request-limits#supported-file-sources)                                                                                                                                                                                                                                                                                                                                                                                       |
| `callback`                                                | string  | *No*     | -          | The callback URL (or Webhook) used to receive the POST data. see [Webhooks & Callbacks](/api-reference/webhooks). This is only applicable when `async` is set to `true`.                                                                                                                                                                                                                                                                                                                           |
| `margins`                                                 | string  | *No*     | -          | Set custom margins, overriding CSS default margins. Specify the margins in the format `{top} {right} {bottom} {left}`. You can use`px`,`mm`,`cm`or`in`units. Also, you can set margins for all sides at once using a single value.                                                                                                                                                                                                                                                                 |
| `paperSize`                                               | string  | *No*     | `A4`       | Specifies the paper size. Accepts standard sizes like 'Letter', 'Legal', 'Tabloid', 'Ledger', 'A0'–'A6'. You can also set a custom size by providing width and height separated by a space, with optional units: `px` (pixels), `mm` (millimeters), `cm` (centimeters), or `in` (inches). Examples: '200 300', '200px 300px', '200mm 300mm', '20cm 30cm', '6in 8in'.                                                                                                                               |
| `orientation`                                             | string  | *No*     | `Portrait` | Sets the document orientation. Options: `Portrait` for vertical layout, and `Landscape` for horizontal layout.                                                                                                                                                                                                                                                                                                                                                                                     |
| `async`                                                   | boolean | *No*     | `false`    | Set `async` to `true` for long processes to run in the background, API will then return a `jobId` which you can use with the [Background Job Check endpoint](/api-reference/job-check). Also see [Webhooks & Callbacks](/api-reference/webhooks)                                                                                                                                                                                                                                                   |
| `name`                                                    | string  | *No*     | -          | File name for the generated output, the input must be in string format.                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `expiration`                                              | integer | *No*     | `60`       | Set the expiration time for the output link in minutes. After this specified duration, any generated output file(s) will be automatically deleted from [PDF.co Temporary Files Storage](/api-reference/file-upload/overview). The maximum duration for link expiration varies based on your current subscription plan. To store permanent input files (e.g. re-usable images, pdf templates, documents) consider using [PDF.co Built-In Files Storage](https://app.pdf.co/tools/files).            |
| `embedAttachments`                                        | boolean | *No*     | `true`     | Set to true to automatically embeds all attachments from original input email MSG or EML files into the final output PDF. Set it to false if you don't want to embed attachments so it will convert only the body of the input email. True by default.                                                                                                                                                                                                                                             |
| `convertAttachments`                                      | boolean | *No*     | `true`     | Set to false if you don't want to convert attachments from the original email and want to embed them as original files (as embedded PDF attachments). Converts attachments that are supported into PDF format and then merges into output final PDF. The supported attachment types for conversion are: `.eml`, `.html/.htm`, `.pdf`, `.doc`, `.docx`, and `.rtf`. Non-supported file types are added as PDF attachments (Adobe Reader or another viewer may be required to view PDF attachments). |
| `profiles`                                                | object  | *No*     | -          | See [Profiles](/api-reference/profiles) for more information.                                                                                                                                                                                                                                                                                                                                                                                                                                      |
|     [`removeHTMLHeadStyleTags`](#removehtmlheadstyletags) | string  | *No*     | `false`    | Removes default styles from the `<head>` section of Outlook emails to ensure accurate PDF rendering. Set to `'true'` to enable.                                                                                                                                                                                                                                                                                                                                                                    |
|     [`removeHTMLBodyStyleTags`](#removehtmlbodystyletags) | string  | *No*     | `false`    | Removes inline and default styles from the `<body>` section of Outlook emails to ensure accurate PDF rendering. Set to `'true'` to enable.                                                                                                                                                                                                                                                                                                                                                         |
|     [`CustomScript`](#customscript)                       | string  | *No*     | -          | Custom JavaScript code executed on the email content before PDF conversion. Use to modify HTML elements, disable links, or apply custom transformations.                                                                                                                                                                                                                                                                                                                                           |
|     `outputDataFormat`                                    | string  | *No*     | -          | If you require your output as `base64` format, set this to `base64`                                                                                                                                                                                                                                                                                                                                                                                                                                |
|     `DataEncryptionAlgorithm`                             | string  | *No*     | -          | Controls the encryption algorithm used for data encryption. See [User-Controlled Encryption](/knowledgebase/user-controlled-encryption) for more information. The available algorithms are: `AES128`, `AES192`, `AES256`.                                                                                                                                                                                                                                                                          |
|     `DataEncryptionKey`                                   | string  | *No*     | -          | Controls the encryption key used for data encryption. See [User-Controlled Encryption](/knowledgebase/user-controlled-encryption) for more information.                                                                                                                                                                                                                                                                                                                                            |
|     `DataEncryptionIV`                                    | string  | *No*     | -          | Controls the encryption IV used for data encryption. See [User-Controlled Encryption](/knowledgebase/user-controlled-encryption) for more information.                                                                                                                                                                                                                                                                                                                                             |
|     `DataDecryptionAlgorithm`                             | string  | *No*     | -          | Controls the decryption algorithm used for data decryption. See [User-Controlled Encryption](/knowledgebase/user-controlled-encryption) for more information. The available algorithms are: `AES128`, `AES192`, `AES256`.                                                                                                                                                                                                                                                                          |
|     `DataDecryptionKey`                                   | string  | *No*     | -          | Controls the decryption key used for data decryption. See [User-Controlled Encryption](/knowledgebase/user-controlled-encryption) for more information.                                                                                                                                                                                                                                                                                                                                            |
|     `DataDecryptionIV`                                    | string  | *No*     | -          | Controls the decryption IV used for data decryption. See [User-Controlled Encryption](/knowledgebase/user-controlled-encryption) for more information.                                                                                                                                                                                                                                                                                                                                             |

### Profiles examples

#### removeHTMLHeadStyleTags

* **Remove default Outlook styles for accurate PDF conversion**

```json theme={null}
{
  "profiles": {
    "removeHTMLHeadStyleTags": "true",
  }
}
```

#### removeHTMLBodyStyleTags

* **Remove inline and default styles for accurate PDF conversion**

```json theme={null}
{
  "profiles": {
    "removeHTMLBodyStyleTags": "true"
  }
}
```

This example removes all inline and default styles from the `<body>` section of Outlook emails to ensure accurate PDF rendering.

#### CustomScript

```json theme={null}
{
  "profiles": {
    "CustomScript": "document.querySelectorAll('a').forEach(a => { a.href = '#' });"
  }
}
```

This example disables all active links while keeping the link text visible.

## Query parameters

*No query parameters accepted.*

## Responses

| Parameter             | Type    | Description                                                                                                                  |
| --------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `url`                 | string  | Direct URL to the final PDF file stored in S3.                                                                               |
| `outputLinkValidTill` | string  | Timestamp indicating when the output link will expire                                                                        |
| `pageCount`           | integer | Number of pages in the PDF document.                                                                                         |
| `error`               | boolean | Indicates whether an error occurred (`false` means success)                                                                  |
| `status`              | string  | Status code of the request (200, 404, 500, etc.). For more information, see [Response Codes](/api-reference/response-codes). |
| `name`                | string  | Name of the output file                                                                                                      |
| `credits`             | integer | Number of credits consumed by the request                                                                                    |
| `remainingCredits`    | integer | Number of credits remaining in the account                                                                                   |
| `duration`            | integer | Time taken for the operation in milliseconds                                                                                 |

## `Example` Payload

<Note>To see the request size limits, please refer to the [Request Size Limits](/api-reference/url-input-and-request-limits#pdf-co-request-size).</Note>

```json theme={null}
{
  "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/email-to-pdf/sample.eml",
  "embedAttachments": true,
  "convertAttachments": true,
  "paperSize": "Letter",
  "name": "email-with-attachments",
  "async": false
}
```

## `Example` Response

<Note>To see the main response codes, please refer to the [Response Codes](/api-reference/response-codes) page.</Note>

```json theme={null}
{
  "url": "https://pdf-temp-files.s3.amazonaws.com/980bc13f061344809c75e83ce181851c/Contact_us.pdf",
  "pageCount": 3,
  "error": false,
  "status": 200,
  "name": "Contact_us.pdf",
  "remainingCredits": 60637
}
```

<Note>
  **Inconsistent URL Encoding in cURL Output:** When using cURL to make API requests, the output JSON may show URL characters encoded as Unicode escape sequences. For example, the ampersand character (`&`) may appear as `\u0026` in the cURL output. This is normal JSON encoding behavior and does not affect the validity of the URL. The URL will function correctly when used, as JSON parsers automatically decode these escape sequences. If you're parsing the response programmatically, your JSON parser will handle this conversion automatically.
</Note>

## Code Samples

<Tabs>
  <Tab title="CURL">
    ```bash theme={null}
    curl --location --request POST 'https://api.pdf.co/v1/pdf/convert/from/email' \
    --header 'x-api-key: *******************' \
    --header 'Content-Type: application/json' \
    --data-raw '{
    "url": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/email-to-pdf/sample.eml",
    "embedAttachments": true,
    "convertAttachments": true,
    "paperSize": "Letter",
    "name": "email-with-attachments",
    "async": false
    }'
    ```
  </Tab>

  <Tab title="JavaScript/Node.js">
    ```javascript theme={null}
    var request = require('request');

    // You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/pdfdotco/pdf-co-api-samples/tree/master/File%20Upload/    
    var options = {
      'method': 'POST',
      'url': 'https://api.pdf.co/v1/pdf/convert/from/email',
      'headers': {
        'Content-Type': 'application/json',
        'x-api-key': '{{x-api-key}}'
      },
      formData: {
        'url': 'https://pdfco-test-files.s3.us-west-2.amazonaws.com/email-to-pdf/sample.eml',
        'embedAttachments': 'true',
        'convertAttachments': 'true',
        'paperSize': 'Letter',
        'name': 'email-with-attachments',
        'async': 'false'
      }
    };
    request(options, function (error, response) {
      if (error) throw new Error(error);
      console.log(response.body);
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    url = "https://api.pdf.co/v1/pdf/convert/from/email"

    # You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/pdfdotco/pdf-co-api-samples/tree/master/File%20Upload/    
    payload={'url': 'https://pdfco-test-files.s3.us-west-2.amazonaws.com/email-to-pdf/sample.eml',
    'embedAttachments': 'true',
    'convertAttachments': 'true',
    'paperSize': 'Letter',
    'name': 'email-with-attachments',
    'async': 'false'}
    files=[

    ]
    headers = {
        'Content-Type': 'application/json',
        'x-api-key': '{{x-api-key}}'
    }

    response = requests.request("POST", url, headers=headers, json=payload, files=files)

    print(response.text)
    ```
  </Tab>

  <Tab title="C#">
    ```csharp theme={null}
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Threading;

    namespace PDFcoApiExample
    {
        class Program
      {
        // The authentication key (API Key).
        // Get your own by registering at https://app.pdf.co
        const String API_KEY = "***********************************";

        // Source Email file to convert
            // You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/pdfdotco/pdf-co-api-samples/tree/master/File%20Upload/
        const string SourceFileUrl = @"https://pdfco-test-files.s3.us-west-2.amazonaws.com/email-to-pdf/sample.eml";

        // Ouput file path
        const string DestinationFile = @"output.pdf";

        // (!) Make asynchronous job
        const bool Async = true;


        static void Main(string[] args)
        {
          // Create standard .NET web client instance
          WebClient webClient = new WebClient();

          // Set API Key
          webClient.Headers.Add("x-api-key", API_KEY);

          try
          {
            // URL for `PDF FROM Email` API call
            var url = "https://api.pdf.co/v1/pdf/convert/from/email";

            // Prepare requests params as JSON
            Dictionary<string, object> parameters = new Dictionary<string, object>();

            // Link to input EML or MSG file to be converted.
            // You can pass link to file from Google Drive, Dropbox or another online file service that can generate shareable links. 
            // You can also use built-in PDF.co cloud storage located at https://app.pdf.co/files or upload your file as temporary file right before making this API call (see Upload and Manage Files section for more details on uploading files via API).
            parameters.Add("url", SourceFileUrl);

            // True by default. 
            // Set to true to automatically embeds all attachments from original input email MSG or EML fileas files into final output PDF. 
            // Set to false if you don’t want to embed attachments so it will convert only the body of input email.
            parameters.Add("embedAttachments", true);

            // true by default. 
            // Converts attachments that are supported by API (doc, docx, html, png, jpg etc) into PDF and merges into output final PDF. 
            // Non-supported file types are added as PDF attachments (Adobe Reader or another viewer maybe required to view PDF attachments).
            // Set to false if you don’t want to convert attachments from original email and want to embed them as original files (as embedded pdf attachments). 
            parameters.Add("convertAttachments", true);

            // Can be Letter, A4, A5, A6 or custom size like 200x200
            parameters.Add("paperSize", "Letter");

            // Name of output PDF
            parameters.Add("name", "email-with-attachments");

            // Set to true to run as async job in background (recommended for heavy documents).
            parameters.Add("async", Async);

            // Convert dictionary of params to JSON
            string jsonPayload = JsonConvert.SerializeObject(parameters);

            // Execute POST request with JSON payload
            string response = webClient.UploadString(url, jsonPayload);

            // Parse JSON response
            JObject json = JObject.Parse(response);

            if (json["error"].ToObject<bool>() == false)
            {
              // Asynchronous job ID
              string jobId = json["jobId"].ToString();
              // URL of generated JSON file available after the job completion; it will contain URLs of result PDF files.
              string resultFileUrl = json["url"].ToString();

              // Check the job status in a loop. 
              // If you don't want to pause the main thread you can rework the code 
              // to use a separate thread for the status checking and completion.
              do
              {
                string status = CheckJobStatus(jobId); // Possible statuses: "working", "failed", "aborted", "success".

                // Display timestamp and status (for demo purposes)
                Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status);

                if (status == "success")
                {
                  // Download output file
                  webClient.DownloadFile(resultFileUrl, DestinationFile);

                  Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile);
                  break;
                }
                else if (status == "working")
                {
                  // Pause for a few seconds
                  Thread.Sleep(3000);
                }
                else
                {
                  Console.WriteLine(status);
                  break;
                }
              }
              while (true);
            }
            else
            {
              Console.WriteLine(json["message"].ToString());
            }
          }
          catch (WebException e)
          {
            Console.WriteLine(e.ToString());
          }

          webClient.Dispose();


          Console.WriteLine();
          Console.WriteLine("Press any key...");
          Console.ReadKey();
        }

        /// <summary>
        /// Checks Job Status
        /// </summary>
        static string CheckJobStatus(string jobId)
        {
          using (WebClient webClient = new WebClient())
          {
            // Set API Key
                    webClient.Headers.Add("x-api-key", API_KEY);
            
            string url = "https://api.pdf.co/v1/job/check?jobid=" + jobId;

            string response = webClient.DownloadString(url);
            JObject json = JObject.Parse(response);

            return Convert.ToString(json["status"]);
          }
        }
      }
    }
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    import java.io.*;
    import okhttp3.*;
    public class main {
        public static void main(String []args) throws IOException{
            OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
            MediaType mediaType = MediaType.parse("application/json");
              // You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/pdfdotco/pdf-co-api-samples/tree/master/File%20Upload/    
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("url","https://pdfco-test-files.s3.us-west-2.amazonaws.com/email-to-pdf/sample.eml")
                .addFormDataPart("embedAttachments","true")
                .addFormDataPart("convertAttachments","true")
                .addFormDataPart("paperSize","Letter")
                .addFormDataPart("name","email-with-attachments")
                .addFormDataPart("async","false")
                .build();
            Request request = new Request.Builder()
                .url("https://api.pdf.co/v1/pdf/convert/from/email")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("x-api-key", "{{x-api-key}}")
                .build();
            Response response = client.newCall(request).execute();
            System.out.println(response.body().string());
        }
    }
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php

    $curl = curl_init();

    // You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/pdfdotco/pdf-co-api-samples/tree/master/File%20Upload/    
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.pdf.co/v1/pdf/convert/from/email',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('url' => 'https://pdfco-test-files.s3.us-west-2.amazonaws.com/email-to-pdf/sample.eml','embedAttachments' => 'true','convertAttachments' => 'true','paperSize' => 'Letter','name' => 'email-with-attachments','async' => 'false'),
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'x-api-key: {{x-api-key}}'
        ),
    ));

    $response = json_decode(curl_exec($curl));

    curl_close($curl);
    echo "<h2>Output:</h2><pre>", var_export($response, true), "</pre>";
    ```
  </Tab>
</Tabs>
