# Email to Print: Automatically Print PDF Attachments by API

> Build an email to print workflow that sends PDF attachments to physical printers. Follow a Python example, secure intake rules, and reliable retry steps.

Published 2026-11-25 · https://printscaler.com/blog/email-to-print-pdf-attachments

![Email attachments passing through a cloud workflow to an office printer with a secure document intake step](https://printscaler.com/blog/images/email-to-print-pdf-attachments-31.jpg)

An **email to print** workflow watches a mailbox, extracts approved attachments, and sends them to a physical printer without someone opening each message. With PrintScaler, a small email-processing worker can submit PDF attachments through an HTTPS API while an agent connects the destination printer. PrintScaler provides the printing layer; you supply the mailbox and the rules that decide what should print.

This guide builds a practical Python starting point, then explains the security and reliability controls needed before leaving it unattended.

## How email to print works

The workflow has four parts:

1. **A dedicated inbox** receives documents such as supplier invoices, customer purchase orders, or dispatch paperwork.
2. **An email worker** reads messages and checks their attachments against your rules.
3. **PrintScaler** accepts a PDF print request for a specific printer.
4. **The PrintScaler agent** connects that printer to the service through a local computer.

The worker can run on a server, a scheduled container, or another machine with mailbox access. It does not need to be on the printer's network.

The printer-side computer runs the agent for Windows, macOS, Linux, or Raspberry Pi. The agent uses an outbound WebSocket connection, so the standard agent setup does not require opening an inbound firewall port.

This separates email processing from printer connectivity. You can replace the mailbox provider or move the worker without rebuilding the printer connection.

### What this workflow does not do

It does not give your printer an email address or make PrintScaler a hosted email service. It also does not automatically render Word documents, spreadsheets, or HTML email bodies into PDFs.

For this implementation, the contract is deliberately narrow: **one eligible PDF attachment becomes one print request**. Email text, signatures, inline logos, and other attachment types do not print.

## Choose the right email-printing approach

Before writing code, decide how much control you need.

| Approach | Suitable when | Main consideration |
|---|---|---|
| Printer manufacturer's email feature, where available | You need a simple supported-device workflow | Capabilities depend on the manufacturer and model |
| Desktop email rules plus local automation | One workstation handles a small, supervised workload | Processing depends on that workstation and its configuration |
| Mailbox worker plus printing API | You need explicit routing, filtering, retries, or an audit trail | You maintain the email-processing logic |

The API approach is useful when a shared inbox receives documents that must reach a warehouse, office, or branch printer consistently.

For example, a purchasing team might send approved supplier invoices to a dedicated inbox. The worker prints PDF attachments on the accounting printer and records which source message generated each request.

Keep approval separate from printing. An email arriving in a mailbox should not automatically mean its contents are trusted or authorized.

## Step 1: Prepare a dedicated intake mailbox

Use a mailbox reserved for printable documents rather than an employee's normal inbox. This avoids accidentally printing personal attachments, newsletters, or unrelated business correspondence.

Define these rules before connecting anything:

- Who is allowed to submit documents?
- Which attachment types are accepted?
- What is the maximum attachment size?
- Does every approved attachment go to the same printer?
- What happens to rejected or ambiguous messages?
- How long will attachments and processing records be retained?

Start with a single destination printer and PDF-only attachments. Add routing only after the basic workflow behaves predictably.

### Treat sender filtering as a security control

A check against the visible `From` address is not sufficient authentication because that address can be spoofed. Use your mail provider's authenticated intake controls, organizational mail-flow rules, or a gateway that evaluates sender authentication and quarantines failures.

The Python example below assumes messages have already passed that intake policy. Do not expose an unrestricted public mailbox and treat every incoming PDF as permission to print.

Also apply malware scanning and attachment restrictions before processing. A filename ending in `.pdf` is not proof that a file is safe.

## Step 2: Connect and test the destination printer

[Download the PrintScaler agent](https://printscaler.com/download) onto a computer that can already print to the target device. Install it, then enter the pairing code in the PrintScaler dashboard to link the computer.

Next:

1. Confirm the expected printer appears in the dashboard.
2. Print a test page from the dashboard.
3. Record the printer ID for your worker's configuration.
4. Confirm the printer's paper, tray, and default output settings.

For emailed invoices and purchase orders, start with a standard office printer using the intended paper size. If attachments have mixed page dimensions, test representative samples rather than assuming every PDF will fit the same paper.

PrintScaler supports PDF options including copies, duplex, paper size, tray, color, and fit to page. Printer capabilities are readable through the API; use supported values rather than hard-coding assumptions about the device.

## Step 3: Send one PDF before connecting the mailbox

Prove that the printing layer works independently of email. For a PDF attachment already downloaded to disk, send its Base64-encoded bytes using `pdf_base64`:

```python
import base64
import os
from pathlib import Path

import requests

pdf = Path("sample-invoice.pdf").read_bytes()

response = requests.post(
    "https://api.printscaler.com/v1/printjobs",
    headers={
        "Authorization": f"Bearer {os.environ['PRINTSCALER_API_KEY']}",
        "X-Idempotency-Key": "email-print-setup-sample-v1",
    },
    json={
        "printerId": int(os.environ["PRINTSCALER_PRINTER_ID"]),
        "contentType": "pdf_base64",
        "content": base64.b64encode(pdf).decode("ascii"),
        "title": "Email printing setup test",
    },
    timeout=(10, 60),
)
response.raise_for_status()
print(response.text)
```

Install the dependency with `python -m pip install requests`. Keep the API key in a secret store or protected environment configuration, never in an email message or committed source file.

Consult the [print jobs API reference](https://printscaler.com/docs#printjobs) when adding options or persisting the returned job details.

The fixed idempotency key makes this a single logical setup submission. Use a new key for an intentional second test; do not reuse it for different documents.

## Step 4: Build a PDF attachment worker

The following example runs one mailbox pass. It uses IMAP over TLS, reads unseen messages without marking them read during download, and submits eligible PDF attachments.

Configure these environment variables:

- `IMAP_HOST`, `IMAP_USER`, and `IMAP_PASSWORD`
- `PRINTSCALER_API_KEY`
- `PRINTSCALER_PRINTER_ID`

Your provider may require an app password or OAuth instead of password-based IMAP authentication. The example uses password login for clarity; adapt authentication to your provider's supported method.

```python
import base64
import hashlib
import imaplib
import os
from email import policy
from email.parser import BytesParser

import requests

HOST = os.environ["IMAP_HOST"]
USER = os.environ["IMAP_USER"]
PRINTER_ID = int(os.environ["PRINTSCALER_PRINTER_ID"])
MAILBOX = "INBOX"
MAX_PDF_BYTES = 10 * 1024 * 1024  # Application policy, not an API limit


def submit_pdf(pdf, source_id, part_index):
    identity = f"{source_id}:{part_index}"
    key = hashlib.sha256(identity.encode()).hexdigest()

    response = requests.post(
        "https://api.printscaler.com/v1/printjobs",
        headers={
            "Authorization": f"Bearer {os.environ['PRINTSCALER_API_KEY']}",
            "X-Idempotency-Key": key,
        },
        json={
            "printerId": PRINTER_ID,
            "contentType": "pdf_base64",
            "content": base64.b64encode(pdf).decode("ascii"),
            "title": f"Email attachment {key[:12]}",
        },
        timeout=(10, 60),
    )
    response.raise_for_status()
    return response.text


with imaplib.IMAP4_SSL(HOST) as mailbox:
    mailbox.login(USER, os.environ["IMAP_PASSWORD"])
    status, _ = mailbox.select(MAILBOX)
    if status != "OK":
        raise RuntimeError("Cannot open intake mailbox")

    _, validity_data = mailbox.response("UIDVALIDITY")
    if not validity_data or validity_data[0] is None:
        raise RuntimeError("Mailbox UIDVALIDITY is unavailable")
    validity = validity_data[0].decode()

    status, results = mailbox.uid("search", None, "UNSEEN")
    if status != "OK":
        raise RuntimeError("Cannot search intake mailbox")

    for uid in results[0].split():
        try:
            status, fetched = mailbox.uid("fetch", uid, "(BODY.PEEK[])")
            if status != "OK":
                raise RuntimeError("Cannot fetch message")

            raw = next(item[1] for item in fetched if isinstance(item, tuple))
            message = BytesParser(policy=policy.default).parsebytes(raw)
            source = f"{HOST}:{USER}:{MAILBOX}:{validity}:{uid.decode()}"
            candidates = []

            for index, part in enumerate(message.walk()):
                if part.get_content_disposition() != "attachment":
                    continue
                name = part.get_filename() or ""
                if not name.lower().endswith(".pdf"):
                    continue
                pdf = part.get_payload(decode=True) or b""
                if not pdf.startswith(b"%PDF-"):
                    raise ValueError("Attachment failed PDF signature check")
                if len(pdf) > MAX_PDF_BYTES:
                    raise ValueError("Attachment exceeds intake size policy")
                candidates.append((index, pdf))

            if not candidates:
                print(f"Review required: message UID {uid.decode()}")
                continue

            for index, pdf in candidates:
                result = submit_pdf(pdf, source, index)
                print(f"Accepted UID {uid.decode()}, part {index}: {result}")

            status, _ = mailbox.uid("store", uid, "+FLAGS", "(\\Seen)")
            if status != "OK":
                raise RuntimeError("Cannot update message flag")
        except Exception as error:
            print(f"Processing failed for UID {uid.decode()}: {error}")
```

Run this initially against a test mailbox. The 10 MiB threshold is a chosen application policy, not a stated PrintScaler limit. Base64 also increases the request size, so account for memory and HTTP payload limits in your hosting environment.

The PDF signature check catches obvious mismatches; it is not a complete PDF validator or malware scanner. The script also downloads each entire message before inspecting attachments, so enforce message-size limits at intake.

### Why the attachment identity matters

A message can contain several PDFs. Each attachment needs its own stable idempotency key so retrying one message does not submit its already-accepted attachments again.

The example combines the mailbox identity, IMAP UID validity, message UID, and MIME-part position. Including UID validity avoids treating a reused UID after a mailbox reset as the same source message.

This identity protects retries of the same mailbox item. It does not identify a forwarded copy as the same business document. If two separate emails containing the same invoice should count as one request, add a business-level duplicate policy rather than assuming email identity solves that problem.

## Step 5: Replace read flags with durable processing records

The script is a starting point, not a complete production queue. Unread flags are convenient for testing but fragile operational state: a person or another email client can change them.

Before deployment, maintain a durable record for every attachment:

| Record | Why it matters |
|---|---|
| Mailbox identity, UID validity, and UID | Identifies the source mailbox item |
| MIME-part index | Distinguishes attachments within one message |
| Destination printer ID | Preserves the routing decision |
| Idempotency key | Makes retries refer to the same submission |
| Returned print job identifier | Connects intake to print-job tracking |
| Processing status and timestamps | Supports recovery and review |

Persist the routing decision before submission. A configuration change should not silently redirect a retry of an existing attachment to another printer.

Use a single worker initially. Multiple workers require an atomic claim or database uniqueness constraint so they cannot process the same attachment concurrently.

Move rejected messages into a review workflow instead of repeatedly scanning them forever. Log identifiers and error summaries, not attachment bodies, credentials, or sensitive document content.

## Step 6: Separate submission from print completion

A successful API response means the request was accepted; it does not prove that paper emerged from the printer.

PrintScaler exposes job states including `new`, `sent_to_client`, `queued`, `in_progress`, `done`, `error`, `cancelled`, and `expired`. Jobs can queue while the connected computer is offline and print when it returns, subject to their configurable expiration time.

Track the returned job identifier and use [print-job webhooks](https://printscaler.com/docs#webhooks) to update your records. Webhooks are HMAC-SHA256 signed and retried; follow the documented verification procedure and make your receiver safe to process repeated deliveries.

Distinguish at least three application milestones:

- **Validated:** The attachment passed your intake rules.
- **Submitted:** PrintScaler accepted its print request.
- **Reported complete or failed:** The job reached a relevant service state.

Even a reported completion should not be treated as proof that a particular person collected the document. For critical paperwork, define an operational confirmation step appropriate to the workflow.

## Handle retries, backlogs, and reprints deliberately

If a request times out, the worker may not know whether the service accepted it. Retry the same logical submission with the same idempotency key rather than generating a fresh key.

For intentional reprints, create a new application record and new key, linked to the original attachment. Record the reason and operator so a reprint is distinguishable from an automatic retry. The separate guide to [preventing duplicate print jobs](https://printscaler.com/blog/prevent-duplicate-print-jobs) explains that distinction in more detail.

Keep throughput below PrintScaler's limit of 10 requests per second, with a burst allowance of 30. A conservative single-worker queue is usually easier to operate than a sudden flood after a weekend backlog.

Also choose an expiration policy that matches the documents. An old purchase order or dispatch instruction may no longer be useful when an offline computer reconnects. Alert on aging jobs rather than assuming every delayed document should eventually print.

For larger document runs, see the guide to [batch printing PDF files](https://printscaler.com/blog/batch-print-pdf-files-cloud-api).

## Test the workflow before leaving it unattended

Use a small acceptance checklist:

- One email with one PDF prints once.
- One email with two PDFs creates two distinct requests.
- An oversized or invalid attachment goes to review.
- A message without an eligible PDF does not print its body.
- Reprocessing the same mailbox item reuses its submission keys.
- A temporary network failure does not cause a blind new submission.
- An offline printer computer produces a visible backlog and alert.
- An intentional reprint creates a separately auditable request.

Budget by eligible attachments, not emails or pages. PrintScaler pricing is per print request: a multipage PDF submitted once is one request, while three PDFs submitted separately are three requests. Check the [current plans and included usage](https://printscaler.com/pricing) against both expected volume and the number of connected computers.

## Turn an inbox into a controlled printing queue

Reliable email to print is mostly about deciding what may print, assigning each attachment a stable identity, and tracking what happens after submission. Keep email intake, API acceptance, and print completion separate, and failures become easier to investigate without creating extra paper.

Start with one restricted mailbox, one printer, and a handful of representative PDFs. [Create a free PrintScaler account](https://printscaler.com/signup) to connect the printer and test the printing layer before automating the rest.

## Frequently asked questions

### Can I automatically print PDF attachments from email?

Yes. A mailbox worker can retrieve messages, validate PDF attachments, and submit each eligible file to a printing API. With PrintScaler, the destination printer connects through an agent on a computer that can access it.

### Does PrintScaler provide an email address for my printer?

The workflow described here uses your own mailbox and email-processing code. PrintScaler supplies the API and printer connection, not a hosted email inbox.

### Can I use this workflow with Gmail or Microsoft 365?

You can build the intake layer using your provider's supported mailbox API or IMAP access. Authentication and administrative restrictions vary, so the password-based IMAP example may need to be replaced with OAuth or a provider-specific API.

### How do I stop an email attachment from printing twice?

Assign each attachment a stable source identity, persist its processing record, and reuse the same PrintScaler idempotency key for retries. A forwarded or resent email is a different mailbox item, so detecting those duplicates requires an additional business rule.

### Will attachments print if the printer computer is offline?

PrintScaler queues jobs while the connected computer is offline and can print them when it reconnects. Jobs expire after a configurable time, so monitor delayed jobs and choose an expiration policy appropriate to the documents.

### Can I automatically print the email body or Word attachments too?

Not with the PDF-only worker in this guide. Add a separate, controlled rendering or conversion step to create a PDF before submitting it, and treat that step as another security boundary for untrusted content.
