API Reference

This section provides detailed documentation for all classes, methods, and functions in django-forwardemail.

EmailService Class

django_forwardemail.services.EmailService

alias of ForwardEmailService

The main service class for sending emails through ForwardEmail.

send_email Method

classmethod EmailService.send_email(*, to: str, subject: str, text: str, from_email: str | None = None, html: str | None = None, reply_to: str | None = None, request: HttpRequest | None = None, site: Site | None = None, base_url: str | None = None) dict[str, Any]

Send an email through the ForwardEmail API.

Parameters:
  • to – Recipient email address

  • subject – Email subject line

  • text – Plain text email content

  • from_email – Sender email address (optional, uses config default)

  • html – HTML email content (optional)

  • reply_to – Reply-to email address (optional, uses config default)

  • request – Django request object for site detection (optional)

  • site – Django Site object (optional, auto-detected if not provided)

  • base_url – ForwardEmail API base URL (optional, uses default)

Returns:

Dict containing the API response

Raises:
  • ImproperlyConfigured – If site configuration is missing

  • Exception – If email sending fails

Parameters:

  • to (str, required): Recipient email address

  • subject (str, required): Email subject line

  • text (str, required): Plain text email content

  • from_email (str, optional): Sender email address. If not provided, uses configuration default or Django’s DEFAULT_FROM_EMAIL

  • html (str, optional): HTML email content for rich formatting

  • reply_to (str, optional): Reply-to email address

  • request (HttpRequest, optional): Django request object for automatic site detection

  • site (Site, optional): Django Site object for explicit site specification

Returns: None

Raises:

  • EmailConfigurationError: When email configuration is missing or invalid

  • ForwardEmailAPIError: When the ForwardEmail API request fails

  • ValidationError: When email addresses are invalid or malformed

Example:

from django_forwardemail.services import EmailService

EmailService.send_email(
    to='user@example.com',
    subject='Welcome!',
    text='Welcome to our service',
    html='<h1>Welcome to our service</h1>',
    from_email='noreply@example.com',
    reply_to='support@example.com'
)

EmailConfiguration Model

class django_forwardemail.models.EmailConfiguration(*args, **kwargs)[source]

Bases: Model

Email configuration for ForwardEmail API integration.

This model stores the configuration needed to send emails through the ForwardEmail API service, with support for multiple sites.

api_key

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

from_email

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

from_name

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

reply_to

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

site

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

created_at

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

updated_at

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

get_next_by_created_at(*, field=<django.db.models.fields.DateTimeField: created_at>, is_next=True, **kwargs)
get_next_by_updated_at(*, field=<django.db.models.fields.DateTimeField: updated_at>, is_next=True, **kwargs)
get_previous_by_created_at(*, field=<django.db.models.fields.DateTimeField: created_at>, is_next=False, **kwargs)
get_previous_by_updated_at(*, field=<django.db.models.fields.DateTimeField: updated_at>, is_next=False, **kwargs)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

objects = <django.db.models.manager.Manager object>
site_id

Django model for storing site-specific email configurations.

Fields:

  • site (OneToOneField): Reference to Django Site model

  • api_key (CharField): ForwardEmail API key (max 255 characters)

  • from_email (EmailField): Default sender email address (optional)

  • from_name (CharField): Default sender name (optional, max 255 characters)

  • reply_to (EmailField): Default reply-to address (optional)

  • created_at (DateTimeField): Timestamp when configuration was created

  • updated_at (DateTimeField): Timestamp when configuration was last modified

Methods:

EmailConfiguration.__str__()[source]

Return str(self).

Returns a string representation of the configuration.

Example:

from django.contrib.sites.models import Site
from django_forwardemail.models import EmailConfiguration

site = Site.objects.get(domain='example.com')
config = EmailConfiguration.objects.create(
    site=site,
    api_key='your_api_key',
    from_email='noreply@example.com',
    from_name='Example Site'
)

ForwardEmailBackend Class

class django_forwardemail.backends.ForwardEmailBackend(fail_silently: bool = False, **kwargs)[source]

Bases: BaseEmailBackend

Django email backend for ForwardEmail API.

This backend integrates with Django’s email system to send emails through the ForwardEmail API service.

__init__(fail_silently: bool = False, **kwargs)[source]

Initialize the ForwardEmail backend.

Parameters:
  • fail_silently – Whether to suppress exceptions

  • **kwargs – Additional keyword arguments, including ‘site’

send_messages(email_messages: Sequence[EmailMessage]) int[source]

Send one or more EmailMessage objects and return the number of email messages sent.

Parameters:

email_messages – List of Django EmailMessage objects to send

Returns:

Number of successfully sent emails

Django email backend implementation for seamless integration with Django’s email system.

Methods:

ForwardEmailBackend.send_messages(email_messages: Sequence[EmailMessage]) int[source]

Send one or more EmailMessage objects and return the number of email messages sent.

Parameters:

email_messages – List of Django EmailMessage objects to send

Returns:

Number of successfully sent emails

Sends one or more EmailMessage instances.

Parameters:

  • email_messages (list): List of Django EmailMessage instances

Returns: Number of successfully sent messages (int)

Example:

# settings.py
EMAIL_BACKEND = 'django_forwardemail.backends.ForwardEmailBackend'

# Usage with Django's email functions
from django.core.mail import send_mail

send_mail(
    'Subject',
    'Message',
    'from@example.com',
    ['to@example.com']
)

Django Admin Integration

class django_forwardemail.admin.EmailConfigurationAdmin(model, admin_site)[source]

Bases: ModelAdmin

Django admin configuration for EmailConfiguration model.

Provides a user-friendly interface for managing ForwardEmail configurations across multiple sites.

list_display = ('site', 'from_name', 'from_email', 'reply_to', 'updated_at')
search_fields = ('site__domain', 'from_name', 'from_email', 'reply_to')
readonly_fields = ('created_at', 'updated_at')
list_filter = ('site', 'updated_at', 'created_at')
fieldsets = ((None, {'fields': ('site',)}), ('Email Settings', {'description': 'Configure the email settings. The From field in emails will appear as "From Name <from@email.com>"', 'fields': ('api_key', ('from_name', 'from_email'), 'reply_to')}), ('Timestamps', {'classes': ('collapse',), 'fields': ('created_at', 'updated_at')}))
get_queryset(request)[source]

Optimize queryset with select_related.

formfield_for_foreignkey(db_field, request, **kwargs)[source]

Customize the site field to show ordered domains.

property media

Django admin interface for managing email configurations.

Features:

  • List view with site, API key (masked), and email addresses

  • Search functionality by site domain and email addresses

  • Filtering by site and creation date

  • Inline editing capabilities

  • Bulk actions for common operations

Admin Configuration:

# Automatically registered when app is installed
# Provides interface for:
# - Creating new email configurations
# - Editing existing configurations
# - Viewing configuration history
# - Testing email sending

App Configuration

Django app configuration class.

Attributes:

  • default_auto_field: Specifies the default primary key field type

  • name: App name for Django’s app registry

  • verbose_name: Human-readable app name for admin interface

Constants and Settings

API Endpoint:

FORWARDEMAIL_API_URL = 'https://api.forwardemail.net/v1/emails'

Default Configuration Keys:

# Environment variable names
FORWARDEMAIL_API_KEY = 'FORWARDEMAIL_API_KEY'
FORWARDEMAIL_FROM_EMAIL = 'FORWARDEMAIL_FROM_EMAIL'
FORWARDEMAIL_FROM_NAME = 'FORWARDEMAIL_FROM_NAME'
FORWARDEMAIL_REPLY_TO = 'FORWARDEMAIL_REPLY_TO'

Exception Classes

EmailConfigurationError

Raised when email configuration is missing or invalid.

Common Causes:

  • Missing API key

  • Invalid site configuration

  • Malformed configuration data

Example:

try:
    EmailService.send_email(to='user@example.com', subject='Test', text='Test')
except EmailConfigurationError as e:
    print(f"Configuration error: {e}")

ForwardEmailAPIError

Raised when ForwardEmail API requests fail.

Common Causes:

  • Network connectivity issues

  • Invalid API credentials

  • Rate limiting

  • Server errors

Example:

try:
    EmailService.send_email(to='user@example.com', subject='Test', text='Test')
except ForwardEmailAPIError as e:
    print(f"API error: {e}")

ValidationError

Raised when email data validation fails.

Common Causes:

  • Invalid email address format

  • Missing required fields

  • Data type mismatches

Example:

try:
    EmailService.send_email(to='invalid-email', subject='Test', text='Test')
except ValidationError as e:
    print(f"Validation error: {e}")

Utility Functions

Site Detection

Extracts Django Site from request object.

Parameters:

  • request (HttpRequest): Django request object

Returns: Site object or None

Example:

from django_forwardemail.utils import get_site_from_request

def my_view(request):
    site = get_site_from_request(request)
    if site:
        print(f"Current site: {site.domain}")

Configuration Retrieval

Retrieves email configuration for a given site.

Parameters:

  • site (Site, optional): Django Site object

  • request (HttpRequest, optional): Django request object

Returns: EmailConfiguration object or None

Example:

from django_forwardemail.utils import get_email_configuration

config = get_email_configuration(site=my_site)
if config:
    print(f"API key configured: {bool(config.api_key)}")

Email Validation

Validates email address format.

Parameters:

  • email (str): Email address to validate

Returns: bool - True if valid, False otherwise

Example:

from django_forwardemail.utils import validate_email_address

if validate_email_address('user@example.com'):
    print("Valid email address")

Migration Support

The package includes Django migrations for database schema management:

Initial Migration (0001_initial.py):

  • Creates EmailConfiguration model table

  • Sets up foreign key relationship with Django Sites

  • Creates appropriate indexes for performance

Migration Commands:

# Apply migrations
python manage.py migrate django_forwardemail

# Create new migration (if you modify models)
python manage.py makemigrations django_forwardemail

Testing Utilities

Mock Email Service

For testing purposes, you can mock the EmailService:

from unittest.mock import patch
from django.test import TestCase

class MyTestCase(TestCase):
    @patch('django_forwardemail.services.EmailService.send_email')
    def test_email_sending(self, mock_send_email):
        # Your test code here
        mock_send_email.assert_called_once()

Test Email Backend

Use Django’s test email backend for testing:

# settings/test.py
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

Version Information

django_forwardemail.__version__ = '1.0.1'

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

Current package version string.

Example:

import django_forwardemail
print(f"Package version: {django_forwardemail.__version__}")

Logging

The package uses Python’s standard logging module with the logger name django_forwardemail.

Log Levels:

  • DEBUG: Detailed API request/response information

  • INFO: Successful operations and configuration changes

  • WARNING: Recoverable errors and fallback usage

  • ERROR: Failed operations and configuration errors

  • CRITICAL: System-level failures

Example Configuration:

import logging

# Get package logger
logger = logging.getLogger('django_forwardemail')
logger.setLevel(logging.INFO)

# Add handler
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)