Marcio Cunha

How to attach PDF invoices and reports via base64 in email API requests

Learn how to handle PDF documents inside web requests using base64 encoding to integrate invoices and reports directly into your messaging workflows.

Marcio Cunha12 min
Also available in:EspañolPortuguês
Summary
  • Base64 encoding converts binary files into a safe plain text sequence for transport inside JSON payloads.
  • The email API requires specific keys in the POST request body to correctly decode and attach the file.
  • Excessive RAM consumption can occur if heavy files are loaded entirely into the application object tree.
  • Rigorous file type validation prevents corrupted documents from reaching the client inbox.
  • Automating invoices and reports through code eliminates manual errors and accelerates business billing cycles.

The challenge of sending corporate documents through code

When we automate billing systems, the need to attach PDF documents sent via email arises naturally. In practice, this means a system needs to take a locally generated file, transform it into data that the internet understands, and send it to an external service. However, the HTTP requests we use to talk to servers speak a text-based language, while a PDF is a binary file full of specific rules and formatting.

To solve this impasse without corrupting the document along the way, developers rely on a conversion technique called base64. This is a method that translates the bits and bytes of any file into a long string of safe characters, such as common letters and numbers. This way, we can place an entire financial report inside a text data packet like JSON, which is the standard format for information exchange on the modern web.

Understanding base64 encoding in practice

The base64 encoding process works by taking pieces of binary data and remapping them to an alphabet of 64 printable characters. In real life, this is like translating text written in a foreign alphabet into our basic Latin alphabet, ensuring no special character is lost when crossing network boundaries. When applied to a PDF invoice, the file size increases by about 33%, a small price to pay for universal compatibility.

However, this conversion requires careful handling of server memory. If you try to load an entire hundred-page report into RAM to transform it all at once, smaller applications might crash due to lack of resources. Therefore, the engineering behind these routines usually employs stream reading, processing the document in small chunks to keep hardware consumption stable and predictable.

Structuring the HTTP request for the email API

Once the PDF file has been properly converted into base64 text, the next step is to fit it into the JSON structure that will be sent to the email API. Popular market services like SendGrid, Resend, or Mailgun expect to find a list of attachments inside the request payload. Each item in this list must contain the encoded content, the original file name, and the corresponding data type.

To ensure the recipient's email client opens the PDF correctly, the media type field must be filled with the standardized value application/pdf. If this detail is ignored, the email system might treat the attachment as unknown text or a generic file, frustrating the end-user experience. Properly assembling this structure is the heart of technical integration.

Below is a practical example of how to structure this request using the Python programming language:

import base64
import requests

# Reading the PDF file in binary format
with open('invoice_1029.pdf', 'rb') as pdf_file:
    binary_content = pdf_file.read()
    # Converting bytes to base64 string
    pdf_base64 = base64.b64encode(binary_content).decode('utf-8')

# Building the email API payload
payload = {
    'to': '[email protected]',
    'subject': 'Your monthly invoice has arrived',
    'html': '

Hello, please find attached the invoice for the current month.

', 'attachments': [ { 'filename': 'invoice_1029.pdf', 'content': pdf_base64, 'type': 'application/pdf' } ] } # Sending the request to the API response = requests.post('https://api.example.com/v1/email', json=payload) print(response.status_code)

Common pitfalls and error handling

One of the most frequent errors when implementing this routine is forgetting to decode the base64 result into UTF-8 text before inserting it into the JSON. In languages like Python, the conversion function returns a bytes object, which the native JSON encoder does not know how to translate on its own. This results in frustrating serialization exceptions that interrupt the message-sending flow.

Another critical point is the size limit imposed by email APIs. Most services reject requests that exceed a certain megabyte threshold per message, combining the text body and all attachments. If your company generates extremely long reports, the best architectural practice is to host the PDF in cloud storage and send only a secure download link in the body of the email.

Conclusion and operational recommendations

Mastering the delivery of PDF invoices and reports via base64 unlocks a powerful array of automations for any software operation. By understanding that conversion serves to bridge the gap between binary data and JSON-based textual requests, developers gain autonomy to design resilient integrations. The secret to success lies in balancing processed file sizes with the operational limits of the tools used.

Adopting best practices for error handling and memory consumption monitoring ensures your system continues to operate without unpleasant surprises during peak moments. With the right structure implemented, the communication flow with clients becomes fully automated, secure, and free from human errors.