Skip to main content

SendGrid using an httpx client

Project description

Async SendGrid

Python PyPI Latest Release PyPI Downloads License - MIT

A modern, asynchronous SendGrid client built on top of httpx. This library provides a simple and efficient way to send emails using SendGrid's API with Python's async/await syntax.

Features

  • 🚀 Asynchronous API client for SendGrid
  • 🔄 Connection pooling for better performance
  • 📊 OpenTelemetry integration for monitoring
  • 🔍 Detailed error tracking and tracing
  • 🛠️ Customizable configuration
  • 📝 Comprehensive documentation

Installation

Install the package using pip:

pip install sendgrid-async

Quick Start

from async_sendgrid import SendgridAPI
from sendgrid.helpers.mail import Mail

# Initialize the client
sendgrid = SendgridAPI(api_key="YOUR_API_KEY")

# Create and send an email
email = Mail(
    from_email="from@example.com",
    to_emails="to@example.com",
    subject="Hello World",
    plain_text_content="Hello World!",
)

response = await sendgrid.send(email)

Advanced Features

Connection Pooling

Optimize performance with connection pooling:

from async_sendgrid import SendgridAPI
from async_sendgrid.pool import ConnectionPool

pool = ConnectionPool(
    max_connections=20,
    max_keepalive_connections=10,
    keepalive_expiry=10.0,
)

sendgrid = SendgridAPI(
    api_key="YOUR_API_KEY",
    pool=pool,
)

Retry Configuration

By default, requests are automatically retried up to 5 times with exponential backoff on transient failures (429 Too Many Requests, 502, 503, 504, and timeouts).

The delay between retries is calculated as:

delay = backoff_factor * (2 ** attempt) * random(1 - backoff_jitter, 1)

With the defaults (backoff_factor=0.5, backoff_jitter=1.0), delays range from 0 to 1s, 0 to 2s, 0 to 4s, etc. Jitter prevents thundering herd problems when multiple clients retry simultaneously.

Customize the retry behavior through the connection pool:

from async_sendgrid import SendgridAPI
from async_sendgrid.pool import ConnectionPool

pool = ConnectionPool(
    retry_attempts=3,    # Maximum retry attempts (default: 5)
    backoff_factor=1.0,  # Backoff multiplier in seconds (default: 0.5)
    backoff_jitter=0.0,  # Jitter multiplier, 0 to 1 (default: 1.0)
)

sendgrid = SendgridAPI(
    api_key="YOUR_API_KEY",
    pool=pool,
)

To disable retries entirely, set retry_attempts=0:

pool = ConnectionPool(retry_attempts=0)

You can also override the retry strategy per call:

# Override both retry attempts and backoff for this call
response = await sendgrid.send(email, retry=10, backoff=1.0)

# Override just one (the other keeps the pool default)
response = await sendgrid.send(email, retry=3)
response = await sendgrid.send(email, backoff=0.1)

Send emails on behalf of another user

Send emails on behalf of subusers:

sendgrid = SendgridAPI(
    api_key="YOUR_API_KEY",
    on_behalf_of="John Smith",
)

Custom Endpoints

Use custom API endpoints:

sendgrid = SendgridAPI(
    api_key="YOUR_API_KEY",
    endpoint="https://custom.endpoint.com/v3/mail/send",
)

Telemetry Integration

Monitor and trace your SendGrid operations with OpenTelemetry:

Setup

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

# Configure OpenTelemetry
tracer_provider = TracerProvider()
trace.set_tracer_provider(tracer_provider)

# Add your exporter
otlp_exporter = OTLPSpanExporter()
span_processor = BatchSpanProcessor(otlp_exporter)
tracer_provider.add_span_processor(span_processor)

Available Metrics

The library automatically tracks:

HTTP Metrics

  • Status codes
  • Response sizes
  • URLs
  • Methods

SendGrid Metrics

  • Number of recipients
  • Attachment presence
  • Email content type

Configuration

Control telemetry behavior with environment variables:

# Disable telemetry
SENDGRID_TELEMETRY_IS_ENABLED=false

# Custom span name
SENDGRID_TELEMETRY_SPAN_NAME=custom.span.name

Error Handling

Robust error handling for API operations:

try:
    response = await sendgrid.send(email)
except Exception as e:
    # Handle the error
    print(f"Error sending email: {e}")

Development

Setup

# Clone the repository
git clone https://github.com/yourusername/async-sendgrid.git
cd async-sendgrid

# Install development dependencies
pip install -e ".[test]"

Testing

# Run all tests
pytest

# Run with coverage
pytest --cov=async_sendgrid

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sendgrid_async-2.2.0.tar.gz (9.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sendgrid_async-2.2.0-py3-none-any.whl (12.3 kB view details)

Uploaded Python 3

File details

Details for the file sendgrid_async-2.2.0.tar.gz.

File metadata

  • Download URL: sendgrid_async-2.2.0.tar.gz
  • Upload date:
  • Size: 9.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for sendgrid_async-2.2.0.tar.gz
Algorithm Hash digest
SHA256 f5f7d37cae21859fb79f62d91dd3dd793cb4f878d373cba4ca62dea3c659f7de
MD5 c4a42e90da03a83500b5f759c5e485f3
BLAKE2b-256 5681ece3b6f55482a62425aaed18f3d2939280f1b9131b61adaabd28f19decb3

See more details on using hashes here.

Provenance

The following attestation bundles were made for sendgrid_async-2.2.0.tar.gz:

Publisher: release.yml on EM51641/async-sendgrid-

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file sendgrid_async-2.2.0-py3-none-any.whl.

File metadata

  • Download URL: sendgrid_async-2.2.0-py3-none-any.whl
  • Upload date:
  • Size: 12.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for sendgrid_async-2.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 60fdf982e4767b265fb0785c9c7ac3df5a0abfe669e7f8e6a5434acb58cd2eac
MD5 77d2872885af112e81bf795fcc8229ee
BLAKE2b-256 aa0cc061019daaca19fa02150f1d61afe4fdd73b48a92645aa5500665bbe649f

See more details on using hashes here.

Provenance

The following attestation bundles were made for sendgrid_async-2.2.0-py3-none-any.whl:

Publisher: release.yml on EM51641/async-sendgrid-

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page