PDF from Email#

Available Methods#

/pdf/convert/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.

  • Method: POST

  • Endpoint: /v1/pdf/convert/from/html

Attributes#

Note

Attributes are case-sensitive and should be inside JSON for POST request.

Attribute

Description

Required

url

URL to the source file. 1

yes

embedAttachments

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.

no

convertAttachments

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 by the PDF.co API (DOC, DOCx, HTML, PNG, JPG etc.) into PDF format and then merges into output final PDF. Non-supported file types are added as PDF attachments (Adobe Reader or another viewer may be required to view PDF attachments).

no

margins

Set to CSS style margins like 10px, 5mm, 5in for all sides or 5px 5px 5px 5px (the order of margins is top, right, bottom, left).

no

paperSize

Letter is set by default. Can be Letter, Legal, Tabloid, Ledger, A0, A1, A2, A3, A4, A5, A6 or a custom size. Custom size can be set in px (pixels), mm or in (inches) with width and height separated by space like this: 200 300, 200px 300px, 200mm 300mm, 20cm 30cm or 6in 8in.

no

orientation

Set to Portrait or Landscape. Portrait by default.

no

async

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 to check the status of the process and retrieve the output while you can proceed with other tasks.

no

name

File name for the generated output, the input must be in string format.

no

expiration

Set the expiration time for the output link in minutes (default is 60 i.e 60 minutes or 1 hour), After this specified duration, any generated output file(s) will be automatically deleted from PDF.co Temporary Files Storage. 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.

no

profiles

Use this parameter to set additional configurations for fine-tuning and extra options. Explore the Profiles section for more. If you prefer you can include paper size and orientation in this attribute as follows: {\"orientation\": \"landscape\", \"paperSize\": \"letter\" }.

no

Query parameters#

No query parameters accepted.

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
}

Response 2#

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

CURL#

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
}'


Code samples#

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/bytescout/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://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/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);
});
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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
payload={'url': 'https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/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)
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;

namespace ByteScoutWebApiExample
{
    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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
    const string SourceFileUrl = @"https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/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"]);
      }
    }
  }
}
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/bytescout/pdf-co-api-samples/tree/master/File%20Upload/
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("url","https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/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());
    }
}
<?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/bytescout/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://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/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>";

On Github#

Footnotes

1

Supports links from Google Drive, Dropbox, and PDF.co Built-In Files Storage. To upload files via the API check out the File Upload section. Note: If you experience intermittent Access Denied or Too Many Requests errors, please try to add cache: to enable built-in URL caching. (e.g cache:https://example.com/file1.pdf) For data security, you have the option to encrypt output files and decrypt input files. Learn more about user-controlled data encryption.

2

Main response codes as follows:

Code

Description

200

Success

400

Bad request. Typically happens because of bad input parameters, or because the input URLs can’t be reached, possibly due to access restrictions like needing a login or password.

401

Unauthorized

402

Not enough credits

445

Timeout error. To process large documents or files please use asynchronous mode (set the async parameter to true) and then check status using the /job/check endpoint. If a file contains many pages then specify a page range using the pages parameter. The number of pages of the document can be obtained using the /pdf/info endpoint.