Skip to main content

Official Python SDK for Huefy - App Mail Templates with dynamic email sending

Project description

Huefy Python SDK

The official Python SDK for the Huefy email sending platform. Send template-based emails with support for multiple providers, automatic retries, and comprehensive error handling.

Installation

PyPI

Install the SDK using pip:

pip install teracrafts-huefy-sdk-python

Development Installation

For development with optional dependencies:

pip install teracrafts-huefy-sdk-python[dev]

For async support:

pip install teracrafts-huefy-sdk-python[async]

Quick Start

from teracrafts_huefy_sdk_python import HuefyClient

# Create client
client = HuefyClient("your-api-key")

# Send email
response = client.send_email(
    template_key="welcome-email",
    recipient="john@example.com",
    data={
        "name": "John Doe",
        "company": "Acme Corp"
    }
)

print(f"Email sent: {response.message_id}")

# Clean up
client.close()

Using Context Manager

from teracrafts_huefy_sdk_python import HuefyClient

with HuefyClient("your-api-key") as client:
    response = client.send_email(
        template_key="welcome-email",
        recipient="john@example.com",
        data={"name": "John Doe"}
    )
    print(f"Email sent: {response.message_id}")
# Client automatically closed

Features

  • Template-based emails - Send emails using predefined templates
  • Multiple providers - Support for SES, SendGrid, Mailgun, Mailchimp
  • Automatic retries - Configurable retry logic with exponential backoff
  • Error handling - Comprehensive exception types for different failure scenarios
  • Bulk emails - Send multiple emails in a single request
  • Health checks - Monitor API health status
  • Type hints - Full type annotations for better IDE support
  • Pydantic models - Data validation and serialization
  • Context manager - Automatic resource cleanup
  • Python 3.8+ - Compatible with Python 3.8 and later versions

Configuration

Basic Configuration

from teracrafts_huefy_sdk_python import HuefyClient

client = HuefyClient("your-api-key")

Advanced Configuration

from teracrafts_huefy_sdk_python import HuefyClient, HuefyConfig, RetryConfig

config = HuefyConfig(
    connect_timeout=10.0,
    read_timeout=30.0,
    retry_config=RetryConfig(
        enabled=True,
        max_retries=5,
        backoff_factor=1.0,
        max_delay=30.0
    )
)

client = HuefyClient("your-api-key", config)

API Reference

Client Creation

HuefyClient(api_key: str, config: Optional[HuefyConfig] = None)

Creates a new Huefy client with the provided API key and optional configuration.

Parameters:

  • api_key (str): The Huefy API key
  • config (HuefyConfig, optional): Client configuration

Raises:

  • ValueError: If api_key is None or empty

Email Operations

send_email(template_key: str, recipient: str, data: Dict[str, Any], provider: Optional[EmailProvider] = None) -> SendEmailResponse

Sends a single email using a template.

from teracrafts_huefy_sdk_python import EmailProvider

response = client.send_email(
    template_key="welcome-email",
    recipient="john@example.com",
    data={
        "name": "John Doe",
        "company": "Acme Corp"
    },
    provider=EmailProvider.SENDGRID  # Optional
)

send_bulk_emails(requests: List[SendEmailRequest]) -> BulkEmailResponse

Sends multiple emails in a single request.

from teracrafts_huefy_sdk_python import SendEmailRequest

requests = [
    SendEmailRequest(
        template_key="welcome-email",
        recipient="john@example.com",
        data={"name": "John Doe"}
    ),
    SendEmailRequest(
        template_key="welcome-email",
        recipient="jane@example.com",
        data={"name": "Jane Doe"}
    )
]

response = client.send_bulk_emails(requests)

health_check() -> HealthResponse

Checks the API health status.

health = client.health_check()
print(f"API Status: {health.status}")

Resource Management

close() -> None

Closes the HTTP session and releases resources.

client.close()

Context Manager Support

with HuefyClient("api-key") as client:
    # Use client
    pass
# Automatically closed

Error Handling

The SDK provides specific exception types for different failure scenarios:

from teracrafts_huefy_sdk_python import (
    HuefyError,
    AuthenticationError,
    TemplateNotFoundError,
    RateLimitError,
    ProviderError,
    NetworkError,
    ValidationError
)

try:
    response = client.send_email(
        template_key="welcome-email",
        recipient="john@example.com",
        data={"name": "John Doe"}
    )
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except TemplateNotFoundError as e:
    print(f"Template '{e.template_key}' not found")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ProviderError as e:
    print(f"Provider {e.provider} error: {e.provider_code}")
except NetworkError as e:
    print(f"Network error: {e}")
except ValidationError as e:
    print(f"Validation error: {e}")
except HuefyError as e:
    print(f"Huefy error: {e}")

Exception Types

  • AuthenticationError - Invalid API key or authentication failure
  • TemplateNotFoundError - Specified template doesn't exist
  • InvalidTemplateDataError - Template data validation failed
  • InvalidRecipientError - Invalid recipient email address
  • ProviderError - Email provider rejected the message
  • RateLimitError - Rate limit exceeded
  • NetworkError - Network connectivity issues
  • TimeoutError - Request timeout
  • ValidationError - Request validation failed
  • HuefyError - Base exception for all SDK errors

Models

EmailProvider

Supported email providers:

from teracrafts_huefy_sdk_python import EmailProvider

EmailProvider.SES        # Amazon SES
EmailProvider.SENDGRID   # SendGrid
EmailProvider.MAILGUN    # Mailgun
EmailProvider.MAILCHIMP  # Mailchimp Transactional

SendEmailRequest

Email request model:

from teracrafts_huefy_sdk_python import SendEmailRequest, EmailProvider

request = SendEmailRequest(
    template_key="welcome-email",
    recipient="john@example.com",
    data={"name": "John Doe"},
    provider=EmailProvider.SES  # Optional
)

SendEmailResponse

Email response model:

response = client.send_email(...)
print(f"Message ID: {response.message_id}")
print(f"Status: {response.status}")
print(f"Provider: {response.provider}")
print(f"Timestamp: {response.timestamp}")

Configuration

HuefyConfig

Client configuration:

from teracrafts_huefy_sdk_python import HuefyConfig

config = HuefyConfig(
    connect_timeout=10.0,                 # Connection timeout in seconds
    read_timeout=30.0,                    # Read timeout in seconds
    retry_config=RetryConfig(...)         # Retry configuration
)

RetryConfig

Retry behavior configuration:

from teracrafts_huefy_sdk_python import RetryConfig

retry_config = RetryConfig(
    enabled=True,           # Enable retries
    max_retries=3,          # Maximum number of retries
    backoff_factor=0.5,     # Backoff factor for exponential delay
    max_delay=30.0          # Maximum delay between retries
)

# Disable retries
retry_config = RetryConfig.disabled()

Retries are automatically performed for:

  • Network errors
  • Timeout errors
  • Rate limit errors (429)
  • Server errors (5xx)

Examples

Basic Email Sending

from teracrafts_huefy_sdk_python import HuefyClient

with HuefyClient("your-api-key") as client:
    response = client.send_email(
        template_key="welcome-email",
        recipient="user@example.com",
        data={
            "name": "John Doe",
            "company": "Acme Corp",
            "signup_date": "2024-01-01"
        }
    )
    print(f"Welcome email sent: {response.message_id}")

Bulk Email Sending

from teracrafts_huefy_sdk_python import HuefyClient, SendEmailRequest

# Prepare multiple email requests
requests = [
    SendEmailRequest(
        template_key="newsletter",
        recipient="john@example.com",
        data={"name": "John", "topic": "Product Updates"}
    ),
    SendEmailRequest(
        template_key="newsletter",
        recipient="jane@example.com",
        data={"name": "Jane", "topic": "Product Updates"}
    )
]

with HuefyClient("your-api-key") as client:
    response = client.send_bulk_emails(requests)
    
    successful = sum(1 for result in response.results if result.success)
    failed = len(response.results) - successful
    
    print(f"Bulk email completed: {successful} sent, {failed} failed")

Error Handling with Specific Provider

from teracrafts_huefy_sdk_python import (
    HuefyClient,
    EmailProvider,
    ProviderError,
    RateLimitError
)

with HuefyClient("your-api-key") as client:
    try:
        response = client.send_email(
            template_key="transactional-email",
            recipient="customer@example.com",
            data={"order_id": "12345", "amount": "$99.99"},
            provider=EmailProvider.SENDGRID
        )
        print(f"Order confirmation sent: {response.message_id}")
        
    except ProviderError as e:
        print(f"SendGrid error [{e.provider_code}]: {e.message}")
        # Maybe retry with different provider
        
    except RateLimitError as e:
        print(f"Rate limited. Retry after {e.retry_after} seconds")
        # Implement backoff logic

Health Check Monitoring

from teracrafts_huefy_sdk_python import HuefyClient, NetworkError

def check_api_health():
    try:
        with HuefyClient("your-api-key") as client:
            health = client.health_check()
            print(f"API Status: {health.status}")
            print(f"Timestamp: {health.timestamp}")
            if health.version:
                print(f"Version: {health.version}")
            return health.status == "healthy"
    except NetworkError:
        print("API is unreachable")
        return False
    except Exception as e:
        print(f"Health check failed: {e}")
        return False

if check_api_health():
    print("✅ API is healthy")
else:
    print("❌ API is unhealthy")

Testing

Run the test suite:

pytest

Run tests with coverage:

pytest --cov=teracrafts_huefy_sdk_python --cov-report=html

Run specific test file:

pytest tests/test_client.py -v

Development

Setup Development Environment

# Clone the repository
git clone https://github.com/teracrafts/huefy-sdk.git
cd huefy-sdk/sdks/python

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode
pip install -e .[dev]

# Install pre-commit hooks
pre-commit install

Code Quality

Run code formatting:

black teracrafts_huefy_sdk_python tests
isort teracrafts_huefy_sdk_python tests

Run linting:

flake8 teracrafts_huefy_sdk_python tests
mypy teracrafts_huefy_sdk_python

Building Distribution

python -m build

Requirements

  • Python 3.8 or later
  • Valid Huefy API key

Dependencies

License

MIT License - see LICENSE file for details.

Support

For support and questions:

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

teracrafts_huefy_sdk_python-2.1.1.tar.gz (21.9 kB view details)

Uploaded Source

Built Distribution

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

teracrafts_huefy_sdk_python-2.1.1-py3-none-any.whl (15.3 kB view details)

Uploaded Python 3

File details

Details for the file teracrafts_huefy_sdk_python-2.1.1.tar.gz.

File metadata

File hashes

Hashes for teracrafts_huefy_sdk_python-2.1.1.tar.gz
Algorithm Hash digest
SHA256 89690297aea97559f64c43ced9076be875c56b06e4aeecdb8627c3ec394c1398
MD5 f4c58d29ce6d8444eafbe0c2b83f9b45
BLAKE2b-256 3eee6ee02dfba92c69855077f93047946e8d2091f2a200c6c6402ad0bbede2ab

See more details on using hashes here.

File details

Details for the file teracrafts_huefy_sdk_python-2.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for teracrafts_huefy_sdk_python-2.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4ea1700cf45542de1dd945f91b7798d4eeb8aa429a5edcdf7d3f79bff1563625
MD5 0654a6ecd2c787175544e5ed1042b434
BLAKE2b-256 6627d9c979665a1ab422bb22a60b1d5d6126cf70e30c6d4044f97898d58e70aa

See more details on using hashes here.

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