Email API•3 min read

Sending File Attachments Through the Piisend Email API

Learn how to send transactional email files and documents using the Piisend Email API. This guide covers base64 encoding for attachments, including PDFs and invoices, directly in your API requests.

Sending File Attachments Through the Piisend Email API

Section 1

Attaching Files to Your Transactional Emails with Piisend

Piisend's Email API allows you to easily include file attachments with your transactional emails, such as PDF invoices, tickets, or reports. This feature is crucial for many business workflows, ensuring your users receive all necessary documents directly in their inbox. Our API supports up to 5 attachments per email, with a combined total size limit of 5 MiB. All attachments must be base64 encoded before being sent to the API.

Section 2

Preparing Attachments: Base64 Encoding Your Files

Before you can send a file through the Piisend API, it must be converted into a base64 string. This encoding transforms binary data into an ASCII string format that can be safely transmitted within a JSON payload. Most programming languages provide built-in functions for base64 encoding. Here's an example using Python to encode a PDF file:

python
1import base64
2
3def encode_file_to_base64(filepath):
4 with open(filepath, "rb") as file:
5 encoded_string = base64.b64encode(file.read()).decode('utf-8')
6 return encoded_string
7
8# Example usage:
9file_path = "invoice.pdf"
10base64_content = encode_file_to_base64(file_path)
11print(f"Base64 content length: {len(base64_content)}")

Section 3

Sending a Single File Attachment via Piisend API

Once your file is base64 encoded, you can include it in the attachments array within your email send request. Each attachment object requires a filename, content (the base64 string), and an optional content_type. The content_type helps email clients display the attachment correctly. Here's how to send an email with a single attachment using curl:

bash
1curl -X POST https://api.piisend.com/api/v1/emails \
2 -H "Authorization: Bearer YOUR_API_KEY" \
3 -H "Content-Type: application/json" \
4 -d '{
5 "to": ["recipient@example.com"],
6 "subject": "Your Invoice from Piisend",
7 "html": "<p>Please find your invoice attached.</p>",
8 "attachments": [
9 {
10 "filename": "invoice.pdf",
11 "content": "JVBERi0xLjQKJcOkw... (base64 content here) ...",
12 "content_type": "application/pdf"
13 }
14 ]
15 }'

Section 4

Including Multiple Attachments in One Email

Piisend supports sending up to five attachments in a single email, provided their combined size does not exceed 5 MiB. To send multiple files, simply add more objects to the attachments array in your API request. This is particularly useful for sending a set of related documents, like an order confirmation with a warranty card and a user manual. Here's a JavaScript example:

javascript
1const fetch = require('node-fetch');
2const fs = require('fs');
3
4const API_KEY = 'YOUR_API_KEY';
5const API_URL = 'https://api.piisend.com/api/v1/emails';
6
7// Helper function to encode file to base64
8function encodeFileToBase64(filePath) {
9 const fileContent = fs.readFileSync(filePath);
10 return fileContent.toString('base64');
11}
12
13async function sendEmailWithMultipleAttachments() {
14 const invoiceContent = encodeFileToBase64('invoice.pdf');
15 const termsContent = encodeFileToBase64('terms_and_conditions.docx');
16
17 const response = await fetch(API_URL, {
18 method: 'POST',
19 headers: {
20 'Authorization': `Bearer ${API_KEY}`,
21 'Content-Type': 'application/json'
22 },
23 body: JSON.stringify({
24 to: ['customer@example.com'],
25 subject: 'Your Order Confirmation and Documents',
26 html: '<p>Thank you for your order! Please find your invoice and terms attached.</p>',
27 attachments: [
28 {
29 filename: 'invoice.pdf',
30 content: invoiceContent,
31 content_type: 'application/pdf'
32 },
33 {
34 filename: 'terms_and_conditions.docx',
35 content: termsContent,
36 content_type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
37 }
38 ]
39 })
40 });
41
42 const data = await response.json();
43 console.log(data);
44}
45
46sendEmailWithMultipleAttachments();

Section 5

Best Practices for Transactional Email Attachments

When sending transactional email files, consider these best practices to ensure optimal deliverability and user experience. Always use descriptive filenames so recipients can easily identify the content. Keep attachment sizes as small as possible; while Piisend supports up to 5 MiB, smaller files load faster and are less likely to trigger spam filters. For very large files, consider linking to a hosted file instead of attaching it directly, providing a better experience for your users and reducing email size.

Start sending

Ship transactional email in minutes

Create an API key, verify a domain, and send your first message with Piisend.