SparkPost Python API Client
The `sparkpost` library is the official Python API client for SparkPost, an enterprise email sending and analytics platform. It provides a straightforward interface to interact with SparkPost's REST API, covering functionalities like sending transmissions, managing templates, and accessing suppression lists. It is actively maintained, with regular updates focused on bug fixes, security enhancements, and new API features. The current version is 1.3.10.
Common errors
-
sparkpost.exceptions.SparkPostAPIException: 401 Unauthorized
cause The SparkPost API key provided is missing, invalid, or does not have the necessary permissions for the requested operation.fixVerify that the `SPARKPOST_API_KEY` environment variable or the key passed to `SparkPost()` constructor is correct and active. Ensure it has the 'Send via SMTP' and 'Transmissions: Read/Write' permissions (or similar, depending on the operation). -
sparkpost.exceptions.SparkPostAPIException: 400 Bad Request - 'recipient address is required'
cause The `recipients` parameter in the `transmissions.send()` call is either empty, malformed, or missing the 'address' key for one or more recipients.fixEnsure the `recipients` list contains dictionaries, each with at least an 'address' key and a valid email string. Example: `recipients=[{'address': 'test@example.com'}]`. -
ImportError: cannot import name 'SparkPost' from 'sparkpost'
cause Python cannot find the `SparkPost` class within the `sparkpost` package. This usually means the library is not installed, or there's a local file/directory named `sparkpost.py` or `sparkpost` shadowing the actual library.fixFirst, ensure the library is installed with `pip install sparkpost`. If the problem persists, check your project directory and Python path for any files or directories named `sparkpost.py` or `sparkpost` that might be causing a conflict.
Warnings
- deprecated The direct URI parameter support for the 'transmissions list' endpoint has been deprecated. While still functional, it's recommended to migrate to updated methods or client versions that handle this gracefully.
- gotcha When handling API errors, ensure you catch `SparkPostAPIException` for specific details. Older versions (pre-1.3.3) had issues returning proper exceptions for some underlying API errors, potentially masking the true problem.
- gotcha Sending emails with non-ASCII characters (e.g., emojis) in the message body may have inconsistent behavior across different minor versions if not handled correctly by the library's encoding.
Install
-
pip install sparkpost
Imports
- SparkPost
from sparkpost import SparkPost
Quickstart
import os
from sparkpost import SparkPost
from sparkpost.exceptions import SparkPostAPIException
# Retrieve SparkPost API key and other details from environment variables
# It is highly recommended to use environment variables or a secret management system
sparkpost_api_key = os.environ.get('SPARKPOST_API_KEY', 'YOUR_SPARKPOST_API_KEY')
from_email = os.environ.get('SPARKPOST_FROM_EMAIL', 'test@example.com')
recipient_email = os.environ.get('SPARKPOST_TEST_EMAIL', 'recipient@example.com')
if not sparkpost_api_key or sparkpost_api_key == 'YOUR_SPARKPOST_API_KEY':
print("WARNING: SPARKPOST_API_KEY environment variable not set or placeholder used.\nCannot send email without a valid API key.")
else:
try:
sp = SparkPost(sparkpost_api_key)
response = sp.transmissions.send(
recipients=[{'address': recipient_email}],
html='<p>Hello from <b>SparkPost Python</b> client!</p>',
from_email=from_email,
subject='Test Email from Python SparkPost'
)
print("Email sent successfully!")
print(f"Transmission ID: {response['results']['id']}")
print(f"Accepted recipients: {response['results']['total_accepted_recipients']}")
except SparkPostAPIException as e:
print(f"SparkPost API Error: {e.status} {e.message} - {e.errors}")
except Exception as e:
print(f"An unexpected error occurred: {e}")