SparkPost Python API Client

1.3.10 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the SparkPost client and send a simple HTML email. Ensure your `SPARKPOST_API_KEY`, `SPARKPOST_FROM_EMAIL`, and `SPARKPOST_TEST_EMAIL` environment variables are set. The example includes basic error handling for `SparkPostAPIException`.

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}")

view raw JSON →