Python API¶
Sending from Python¶
You can send email in two ways, first the conventional way described in the Django documentation and second by using EmailHub’s template feature.
The conventional method is suited for email for which you don’t need editable
templates or draft mode. The EmailHub email backend handle the linking with
users if a user email is found in the to
, cc
or bcc
fields.
The EmailHub template method uses the EmailFromTemplate
class to create
an email instance from a template:
from emailhub.utils.email import EmailFromTemplate
msg = EmailFromTemplate(
'template-slug-name', lang='en').send_to(user)
With custom context variables:
from emailhub.utils.email import EmailFromTemplate
msg = EmailFromTemplate('template-slug-name',
lang='en',
extra_context={
'somevar': some_var,
'someothervar': some_other_var,
}).send_to(user)
At this point the message isn’t really sent, it is wither in draft
or in
pending
state. You can the email right away by calling send
.
You can force send a message like so:
msg.send(force=True)
If the force
argument is False
(default) it will just mark the email
as pending so it will be sent in batch with the cron job.
Email states¶
Email messages are always in one of the following state:
- draft: message is still editable, will not be sent.
- pending: message is waiting to be sent (via cron job)
- locked: message is being sent, will result in either
sent
orerror
state. - sent: message has been sent (is an archive)
- error: message has been sent, but the server returned an error. Sending will be retried until
EMAILHUB_SEND_MAX_RETRIES
has been reached.
>>> print(msg.state)
'draft'
>>> print(msg.is_draft)
True
>>> print(msg.is_pending)
False
>>> print(msg.is_locked)
False
>>> print(msg.is_sent)
False
>>> print(msg.is_error)
False