Sending PDF Attachments from Python with the Piisend API
Learn how to send transactional emails with PDF attachments using Python and the Piisend API. This tutorial covers base64 encoding, integrating with the Piisend REST API, and best practices for sending files like invoices or tickets.
Section 1
Why Send Attachments with Transactional Emails?
Transactional emails often require more than just text or HTML; they frequently need to include files like invoices, tickets, or reports. Piisend's Email API simplifies the process of attaching files, ensuring your critical documents reach your users reliably. This guide will walk you through sending python email attachments using Base64 encoding with our robust API.
Section 2
Base64 Encoding Your Attachments in Python
Before sending any file via the Piisend API, it must be encoded into a Base64 string. This process converts binary data into an ASCII string format that can be safely transmitted within a JSON payload. For send PDF email API use cases, this is a crucial first step. Here's how to encode a PDF file in Python:
1import base642 3def encode_file_to_base64(filepath):4 with open(filepath, "rb") as file:5 return base64.b64encode(file.read()).decode("utf-8")6 7# Example usage for a PDF invoice8pdf_filepath = "invoice.pdf"9base64_content = encode_file_to_base64(pdf_filepath)10print(f"Base64 encoded content (first 50 chars): {base64_content[:50]}...")Section 3
Integrating Python Attachments with the Piisend API
Once your file is Base64 encoded, you can include it in the attachments array of your Piisend API request. Each attachment requires content_b64, filename, and content_type. We recommend using the httpx library for making asynchronous HTTP requests in Python, which is efficient for transactional email python applications.
1import httpx2import base643 4# Assume encode_file_to_base64 function from previous step5def encode_file_to_base64(filepath):6 with open(filepath, "rb") as file:7 return base64.b64encode(file.read()).decode("utf-8")8 9# Prepare your attachment10pdf_filepath = "invoice.pdf"11base64_pdf_content = encode_file_to_base64(pdf_filepath)12 13# Piisend API details14PIISEND_API_KEY = "YOUR_API_KEY"15API_ENDPOINT = "https://api.piisend.com/api/v1/emails"16 17payload = {18 "to": ["customer@example.com"],19 "subject": "Your Piisend Invoice",20 "html": "<h1>Thank you for your purchase!</h1><p>Please find your invoice attached.</p>",21 "text": "Thank you for your purchase! Please find your invoice attached.",22 "attachments": [23 {24 "content_b64": base64_pdf_content,25 "filename": "invoice.pdf",26 "content_type": "application/pdf"27 }28 ]29}30 31headers = {32 "Authorization": f"Bearer {PIISEND_API_KEY}",33 "Content-Type": "application/json"34}35 36try:37 response = httpx.post(API_ENDPOINT, json=payload, headers=headers)38 response.raise_for_status() # Raise an exception for HTTP errors39 print("Email sent successfully!")40 print(response.json())41except httpx.HTTPStatusError as e:42 print(f"HTTP error occurred: {e.response.status_code} - {e.response.text}")43except httpx.RequestError as e:44 print(f"An error occurred while requesting: {e}")Section 4
Managing Multiple Attachments and File Size Limits
Piisend's API allows you to include multiple attachments in a single email by adding more objects to the attachments array. However, it's important to be mindful of total email size. While Piisend supports generous limits, excessively large emails can impact deliverability and recipient experience. Always ensure your base64 attachments are within reasonable bounds, typically under 10-20 MB total for optimal performance. For very large files, consider linking to a hosted file instead of attaching it directly.