API Reference
This section documents the public classes and methods in django-forwardemail.
ForwardEmailService
- class django_forwardemail.services.ForwardEmailService[source]
Bases:
objectService class for sending emails through the ForwardEmail API.
This service handles authentication, email formatting, and API communication with the ForwardEmail service, with support for multi-site configurations.
- DEFAULT_BASE_URL = 'https://api.forwardemail.net'
- classmethod 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][source]
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
- static extract_email(email_string: str) str[source]
Extract clean email address from a string that may contain a name.
- Parameters:
email_string – Email string like “Name <email@domain.com>” or “email@domain.com”
- Returns:
Clean email address
The main service class for sending email through the ForwardEmail API.
EmailService is a backward-compatible alias for ForwardEmailService.
send_email
- classmethod ForwardEmailService.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][source]
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
A keyword-only classmethod that sends a single email through the ForwardEmail API.
Parameters:
to(str, required): Recipient email addresssubject(str, required): Email subject linetext(str, required): Plain text email contentfrom_email(str, optional): Sender email address. If omitted, the sender is built from the site’sEmailConfigurationhtml(str, optional): HTML email content for rich formattingreply_to(str, optional): Reply-to email address. If omitted, the site’s configuredreply_tois usedrequest(HttpRequest, optional): Django request object for automatic site detectionsite(Site, optional): Django Site object for explicit site specificationbase_url(str, optional): Override for the ForwardEmail API base URL
Returns: dict[str, Any] – the JSON response from the ForwardEmail API.
Raises:
django.core.exceptions.ImproperlyConfigured: when the site cannot be determined, or the resolved site has noEmailConfigurationException: when the API request fails (a non-200 response or a network error such as a timeout or connection error)
Example:
from django_forwardemail.services import ForwardEmailService
ForwardEmailService.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',
)
extract_email
- static ForwardEmailService.extract_email(email_string: str) str[source]
Extract clean email address from a string that may contain a name.
- Parameters:
email_string – Email string like “Name <email@domain.com>” or “email@domain.com”
- Returns:
Clean email address
A static method that returns the bare email address from a string. Given
"Name <email@domain.com>" it returns "email@domain.com"; a string that
is already a bare address is returned unchanged (stripped of whitespace).
EmailConfiguration Model
- class django_forwardemail.models.EmailConfiguration(*args, **kwargs)[source]
Bases:
ModelEmail 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.parentis aForwardManyToOneDescriptorinstance.
- 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. Each Django
Site has exactly one configuration (enforced by
unique_together = [["site"]]).
Fields (all required except the timestamps):
site(ForeignKey todjango.contrib.sites.models.Site): the site this configuration applies toapi_key(CharField, max length 255): ForwardEmail API keyfrom_email(EmailField): default sender email addressfrom_name(CharField, max length 255): default sender display namereply_to(EmailField): default reply-to addresscreated_at(DateTimeField): set automatically on creationupdated_at(DateTimeField): set automatically on each save
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',
reply_to='support@example.com',
)
ForwardEmailBackend
- class django_forwardemail.backends.ForwardEmailBackend(fail_silently: bool = False, **kwargs)[source]
Bases:
BaseEmailBackendDjango email backend for ForwardEmail API.
This backend integrates with Django’s email system to send emails through the ForwardEmail API service.
Django email backend that routes Django’s standard email helpers through the
ForwardEmail API. It supports EmailMessage and EmailMultiAlternatives
(HTML + text), extracts the reply-to address from the message, and accepts an
optional site via the connection or backend kwargs. Because the ForwardEmail
API accepts one recipient per request, the backend sends to the first recipient
of each message.
send_messages
- 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(sequence of DjangoEmailMessageinstances)Returns: the number of successfully sent messages (int). When
fail_silentlyis true, failures are swallowed and excluded from the count.
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:
ModelAdminDjango 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')}))
- formfield_for_foreignkey(db_field, request, **kwargs)[source]
Customize the site field to show ordered domains.
- property media
Django admin interface for managing EmailConfiguration records. It is
registered automatically when the app is installed.
Configuration:
list_display:site,from_name,from_email,reply_to,updated_atsearch_fields:site__domain,from_name,from_email,reply_tolist_filter:site,updated_at,created_atreadonly_fields:created_at,updated_atfieldsets: site, an “Email Settings” group (API key and addresses), and a collapsible “Timestamps” groupThe queryset uses
select_related("site")and the site dropdown is ordered by domain
App Configuration
- class django_forwardemail.apps.DjangoForwardEmailConfig(app_name, app_module)[source]
Bases:
AppConfigDjango app configuration for ForwardEmail integration.
- default_auto_field = 'django.db.models.BigAutoField'
- name = 'django_forwardemail'
- verbose_name = 'Django ForwardEmail'
Django AppConfig for the package.
Attributes:
default_auto_field:"django.db.models.BigAutoField"name:"django_forwardemail"verbose_name:"Django ForwardEmail"
Constants and Settings
API base URL
ForwardEmailService.DEFAULT_BASE_URL is "https://api.forwardemail.net".
Requests are sent to {base_url}/v1/emails. The base URL can be overridden
per call via the base_url argument, or globally via the
FORWARD_EMAIL_BASE_URL Django setting.
Settings
FORWARD_EMAIL_BASE_URL(optional): overrides the ForwardEmail API base URLEMAIL_BACKEND: set to"django_forwardemail.backends.ForwardEmailBackend"to use ForwardEmail with Django’s standard email functions
There are no FORWARDEMAIL_* settings or environment variables – API keys
and addresses live in the EmailConfiguration model.
Errors
The package does not define custom exception classes. Callers should handle:
django.core.exceptions.ImproperlyConfigured– raised bysend_email()when the site cannot be resolved or has noEmailConfigurationException– raised bysend_email()when the ForwardEmail API request fails (a non-200 response or a network error)
Migration Support
The package ships a single initial migration that creates the
EmailConfiguration table and its foreign key to django.contrib.sites.
# Apply migrations
python manage.py migrate
Testing
ForwardEmailService.send_email() issues a single requests.post call and
does not go through Django’s EMAIL_BACKEND. In tests, patch
requests.post rather than relying on the locmem backend:
from unittest.mock import patch
from django.test import TestCase
class MyTestCase(TestCase):
@patch('django_forwardemail.services.requests.post')
def test_email_sending(self, mock_post):
mock_post.return_value.status_code = 200
mock_post.return_value.json.return_value = {}
# ... call code that sends email ...
mock_post.assert_called_once()
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’.
The current package version string.
import django_forwardemail
print(django_forwardemail.__version__)
Logging
The package logs through Python’s standard logging module under the
django_forwardemail logger name.
Log levels used:
DEBUG: ForwardEmail API request and response details (only emitted when DjangoDEBUGis true)INFO: general operational messagesERROR: failed API requests and service errors
Example configuration:
import logging
logger = logging.getLogger('django_forwardemail')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
)
logger.addHandler(handler)