How to Convert Email to PDF with Java

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

This Java walkthrough uses an OkHttp multipart request from a JVM application. It converts an Email (.eml) file into a PDF through the pdfRest Convert to PDF API Tool. The complete sample is included below so Java developers can see the file handling, request construction, and response path together.

Why Email to PDF with Java?

Java services commonly handle structured business events while message files arrive from gateways, records systems, or customer portals. Turning an .eml message into PDF gives the service a shareable record without introducing a separate mail-viewing component.

A Spring-based case service could convert correspondence attached to a complaint, store the returned PDF ID with the case, and let reviewers retrieve the same rendered document from the case screen. The original Email file can remain in the source repository according to its own policy.

OkHttp handles the file upload and response in the same client style used elsewhere in Java integrations. That makes it straightforward to add normal retry, audit, and resource-lifecycle handling around the sample.

Java Code Example for Email to PDF

import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.*;

public class PdfFromEmail {
  // By default, we use the US-based API service. This is the primary endpoint for global use.
  private static final String API_URL = "https://api.pdfrest.com";

  // For GDPR compliance and enhanced performance for European users, replace the URL above
  // with https://eu-api.pdfrest.com. For more information, visit
  // https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  // Converts an Email (.eml) file to PDF by sending the file directly in a
  // multipart request.
  public static void main(String[] args) throws IOException {
    File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.eml");
    Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
    String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY);
    MultipartBody.Builder form =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file",
                inputFile.getName(),
                RequestBody.create(inputFile, MediaType.parse("message/rfc822")))
            .addFormDataPart("output", "pdf_from_email");
    Request request =
        new Request.Builder()
            .url(API_URL + "/pdf")
            .header("Api-Key", apiKey)
            .post(form.build())
            .build();
    send(request);
  }

  private static void send(Request request) throws IOException {
    OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build();
    try (Response response = client.newCall(request).execute()) {
      System.out.println("Result code " + response.code());
      if (response.body() != null) System.out.println(response.body().string());
      if (!response.isSuccessful()) System.exit(1);
    }
  }
}

Source: View the sample on GitHub

Breaking Down the Code

Configure the service and input

// By default, we use the US-based API service. This is the primary endpoint for global use.
  private static final String API_URL = "https://api.pdfrest.com";

  // For GDPR compliance and enhanced performance for European users, replace the URL above
  // with https://eu-api.pdfrest.com. For more information, visit
  // https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

For this Email to PDF example, Java sends the multipart request to /pdf. The Java samples use OkHttp for multipart HTTP requests and dotenv support for repository configuration. The sample project supplies those dependencies; applications that copy the class elsewhere need equivalent dependencies and secure runtime configuration. 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

new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file",
                inputFile.getName(),
                RequestBody.create(inputFile, MediaType.parse("message/rfc822")))
            .addFormDataPart("output", "pdf_from_email");
    Request request =
        new Request.Builder()
            .url(API_URL + "/pdf")
            .header("Api-Key", apiKey)

The Java 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

Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
    String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY);
    MultipartBody.Builder form =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file",
                inputFile.getName(),
                RequestBody.create(inputFile, MediaType.parse("message/rfc822")))
            .addFormDataPart("output", "pdf_from_email");
    Request request =

For the Email to PDF form, okHttp’s MultipartBody.Builder constructs the form and assigns its boundary. Each file part carries a filename and media type, while conversion options are ordinary text parts.

Read the output resource

private static void send(Request request) throws IOException {
    OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build();
    try (Response response = client.newCall(request).execute()) {
      System.out.println("Result code " + response.code());
      if (response.body() != null) System.out.println(response.body().string());
      if (!response.isSuccessful()) System.exit(1);
    }
  }
}

After the Email to PDF call, the response block checks the HTTP status before printing its body. On success, the JSON contains the output resource ID and URL; on failure, the printed body gives the API error detail needed for diagnosis.

Beyond the Tutorial

In this Java 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 Java application’s error handling, retention policy, and delivery workflow.

The repository also provides a JSON-payload Email-to-PDF version for Java. 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.