09-28-2022, 12:28 PM
Send, Receive, and Test Emails in Django
5/5 – (1 vote)
Some time ago, we discovered how to send an email with Python using, a built-in email module. Back then, the focus was made on the delivery of different types of messages via SMTP server. Today, we prepared a similar tutorial but for Django.
This popular Python web framework allows you to accelerate email delivery and make it much easier. And these code samples of sending emails with Django are going to prove that.
[b]A simple code example of how to send an email[/b]
Let’s start our tutorial with a few lines of code that show you how simple it is to send an email in Django. Import send_mail in the beginning of the file:
And call the code below in the necessary place.
These lines are enclosed in the module that is based on . The message delivery is carried out via SMTP host, and all the settings are set by default:
Note that the character set of emails sent with are automatically set to the value of your setting.
You can learn about the other default values here. Most likely you will need to adjust them. Therefore, let’s tweak the settings.py file..
[b]Setting up[/b]
Before actually sending your email, you need to set up for it. So, let’s add some lines to the settings.py file of your Django app.
is different for each email provider you use. For example, if you have a Gmail account and use their SMTP server, you’ll have .
Also, validate other values that are relevant to your email server. Eventually, you need to choose the way to encrypt the mail and protect your user account by setting the variable or .
If you have an email provider that explicitly tells you which option to use, then it’s clear. Otherwise, you may try different combinations using and operators. Note that only one of these options can be set to .
tells Django which custom or predefined email backend will work with.
. You can set up this parameter as well.
[b]SMTP email backend [/b]
In the example above, is specified as . It is the default configuration that uses SMTP server for email delivery. Defined email settings will be passed as matching arguments to .
Unspecified arguments default to.
As well as, you can use:
[b]How to send emails via SMTP [/b]
Once you have that configured, all you need to do to send an email is to import the or from . These functions differ in the connection they use for messages. a separate connection for each message. a single connection to the mail server and is mostly intended to handle mass emailing.
[b]Sending email with send_mail[/b]
This is the most basic function for email delivery in Django. It comprises four obligatory parameters to be specified:, , , and .
In addition to them, you can adjust the following:
For example, it may look like this:
Other functions for email delivery include and . Both are shortcuts to send emails to the recipients predefined in ADMINS and MANAGERS settings respectively.
For them, you can specify such arguments as, , , , and .
The argument is defined by the setting.
[b]What is EmailMessage for? [/b]
If the email backend handles the email sending, the class answers for the message creation. You’ll need it when some advanced features like BCC or an attachment are desirable. That’s how an initialized may look:
In addition to the objects you can see in the example, there are also other optional parameters:
The methods you can use with the class are the following:
[b]How to send multiple emails[/b]
To deliver a message via SMTP, you need to open a connection and close it afterwards. This approach is quite awkward when you need to send multiple transactional emails. Instead, it is better to create one connection and reuse it for all messages.
This can be done with the method that the email backend API has. Check out the following example:
What you can see here is that the connection was opened for, and uses it to send emails #2 and #3. After that, you close the connection manually.
[b]How to send multiple emails with send_mass_mail[/b]
is another option to use only one connection for sending different messages.
Each email message contains a datatuple made of, , , and . Optionally, you can add other arguments that are the same as for .
[b]How to send an HTML email[/b]
All versions starting from 1.7 let you send an email with HTML content using like this:
Older versions users will have to mess about with and its subclass . It lets you include different versions of the message body using the method. For example:
[b]How to send an email with attachments[/b]
In the section, we’ve already mentioned sending emails with attachments. This can be implemented using or methods.
The first one creates and adds a file attachment through three arguments – filename, content, and mime type.
The second method uses a file from a filesystem as an attachment. That’s how each method would look like in practice:
or
[b]Custom email backend[/b]
You’re not limited to the abovementioned email backend options and can tailor your own. For this, you can use standard backends as a reference. Let’s say, you need to create a custom email backend with the connection support required to interact with Amazon SES.
The default SMTP backend will be the reference. First, add a new email option to settings.py.
Make sure that you are allowed to send emails with Amazon SES using these and (or error message will tell you about it :D)
Then create a file your_project_name/email_backend.py with the following content:
This is the minimum needed to send an email using SES. Surely you will need to add some error handling, input sanitization, retries etc. but this is out of our topic.
You might see that we have imported boto3 in the beginning of the file. Don’t forget to install it using a command
It’s not necessary to reinvent the wheel every time you need a custom email backend. You can find already existing libraries, or just receive SMTP credentials in your Amazon console and use the default email backend. It’s just about figuring out the best option for you and your project.
[b]Sending emails using SES from Amazon[/b]
So far, you can benefit from several services that allow you to send transactional emails at ease. If you can’t choose one, check out our blog post about Sendgrid vs. Mandrill vs. Mailgun. It will help a lot. At this point, Mailtrap has launched its own sending solution.
So, you could easily start sending transactional emails in Django using our guide. But today, we’ll discover how to make your Django app send emails via Amazon SES. It is one of the most popular services so far. Besides, you can take advantage of a ready-to-use Django email backend for this service – django-ses.
[b]Set up the library[/b]
You need to execute pip install django-ses to install django-ses. Once it’s done, tweak your settings.py with the following line:
[b]AWS credentials[/b]
Don’t forget to set up your AWS account to get the required credentials – AWS access keys that consist of access key ID and secret access key.
For this, add a user in Identity and Access Management (IAM) service.
Then, choose a user name and Programmatic access type. Attach permission and create a user. Once you’ve done this, you should see AWS access keys. Update your settings.py:
[b]Email sending[/b]
Now, you can send your emails using:
is not the only preset email backend you can leverage. At the end of this article, you’ll find more useful libraries to optimize email delivery of your Django app. But first, a step you should never send emails without.
[b]Testing email sending in Django [/b]
Once you’ve got everything prepared for sending email messages, it is necessary to do some initial testing of your mail server. In Python, this can be done with one command:
This allows you to send emails to your local SMTP server. The DebuggingServer feature won’t actually send the email but will let you see the content of your message in the shell window. That’s an option you can use off-hand.
[b]Django’s TestCase[/b]
TestCase is a solution to test a few aspects of your email delivery. It uses locmem.EmailBackend, which, as you remember, stores messages in the local memory cache – django.core.mail.outbox. So, this test runner does not actually send emails. Once you’ve selected this email backend
you can use the following unit test sample to test your email sending capability.
This code will test not only your email sending but also the correctness of the email subject and message body.
[b]Testing with Mailtrap[/b]
Mailtrap can be a rich solution for testing. First, it lets you test not only the SMTP server but also the email content and do other essential checks from the email testing checklist. Second, it is a rather easy-to-use tool.
All you need to do is to copy the SMTP credentials from your demo inbox and tweak your settings.py. Or you can just copy/paste these four lines from the Integrations section by choosing Django in the pop-up menu.
After that, feel free to send your HTML/CSS email with an attachment to check how it goes.
If there is no message in the Mailtrap Demo inbox or there are some issues with HTML content, you need to polish your code.
[b]Django email libraries to simplify your life[/b]
As a conclusion to this blog post about sending emails with Django, we’ve included a brief introduction of a few libraries that will facilitate your email workflow.
[b]django-anymail[/b]
This is a collection of email backends and webhooks for numerous famous email services including SendGrid, Mailgun, and others. works with the module and normalizes the functionality of transactional email service providers.
[b]django-mailer[/b]
django-mailer is a Django app you can use to queue email sending. With it, scheduling your emails is much easier.
[b]django-post_office[/b]
With this app, you can send and manage your emails. django-post_office offers many cool features like asynchronous email sending, built-in scheduling, multiprocessing, etc.
[b]django-templated-email[/b]
This app is about sending templated emails. In addition to its own functionalities, django-templated-email can be used in tow with to integrate transactional email service providers.
[b]How to receive emails in Django[/b]
To receive emails in Django, it is better to use the django-mailbox development library if you need to import messages from local mailboxes, POP3, IMAP, or directly receive messages from Postfix or Exim4.
While using Django-mailbox, mailbox functions as a message queue that is being gradually processed. The library helps retrieve email messages and then erases them so they are not downloaded again the next time.
Mailbox types supported by django-mailbox: POP3, IMAP, Gmail IMAP with Oauth2 authentication, local file-based mailboxes like Maildir, Mbox, Babyl, MH, or MMDF.
Here’s a step-by-step guide on how to quickly set up your Django-mailbox and start receiving emails.
[b]Installation[/b]
There are two ways to install django-mailbox:
1. From pip:
2. From the github-repository:
When you are done with the installation and checking the configurations, it’s time to receive incoming emails. There are five different ways to do that.
Use the method to collect new messages from the server.
Go to Django Admin, then to ‘Mailboxes’ page, check all the mailboxes you need to receive emails from. At the top of the list with mailboxes, choose the action selector ‘Get new mail’ and click ‘Go’.
Run the management command in
To configure Exim4 to receive incoming mail begin with adding a new router:
In case the email addresses you are trying to add are handled by other routers, disable them. For this change, the contents of must match a colon-delimited list of usernames for which you would like to receive mail.
5. Directly from Postfix
With Postfix get new mail to a script using. The steps to set up receiving incoming mail directly from Postfix are pretty much the same as with Exim4. However, you might need to check out the Postfix pipe documentation.
There’s also an option to subscribe to the incoming signal if you need to process your incoming mail at the time that suits you best.
Use this piece of code to do that:
Keep in mind that this should be loaded to models.py or elsewhere early enough for the signal not to be fired before your signal handler’s registration is processed.
We hope that you find our guide helpful and the list of packages covered help facilitate your email workflow. You can always find more apps at Django Packages.
This article was originally published on Mailtrap’s blog: Sending emails in Django with code examples. We have repurposed it on the Finxter blog with their permission!
5/5 – (1 vote)
Some time ago, we discovered how to send an email with Python using
Code:
smtplibThis popular Python web framework allows you to accelerate email delivery and make it much easier. And these code samples of sending emails with Django are going to prove that.
[b]A simple code example of how to send an email[/b]
Let’s start our tutorial with a few lines of code that show you how simple it is to send an email in Django. Import send_mail in the beginning of the file:
Code:
from django.core.mail import send_mailAnd call the code below in the necessary place.
Code:
send_mail( 'That’s your subject', 'That’s your message body', 'from@yourdjangoapp.com', ['to@yourbestuser.com'], fail_silently=False,
)These lines are enclosed in the
Code:
django.core.mailCode:
smtplibCode:
EMAIL_HOST: 'localhost'
EMAIL_PORT: 25
EMAIL_HOST_USER: (Empty string)
EMAIL_HOST_PASSWORD: (Empty string)
EMAIL_USE_TLS: False
EMAIL_USE_SSL: FalseNote that the character set of emails sent with
Code:
django.core.mailCode:
DEFAULT_CHARSETYou can learn about the other default values here. Most likely you will need to adjust them. Therefore, let’s tweak the settings.py file..
[b]Setting up[/b]
Before actually sending your email, you need to set up for it. So, let’s add some lines to the settings.py file of your Django app.
Code:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.yourserver.com'
EMAIL_PORT = '<your-server-port>'
EMAIL_HOST_USER = 'your@djangoapp.com'
EMAIL_HOST_PASSWORD = 'your-email account-password'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = FalseCode:
EMAIL_HOSTCode:
EMAIL_HOST = ‘smtp.gmail.com’Also, validate other values that are relevant to your email server. Eventually, you need to choose the way to encrypt the mail and protect your user account by setting the variable
Code:
EMAIL_USE_TLSCode:
EMAIL_USE_SSLIf you have an email provider that explicitly tells you which option to use, then it’s clear. Otherwise, you may try different combinations using
Code:
TrueCode:
FalseCode:
TrueCode:
EMAIL_BACKENDCode:
EMAIL_HOST[b]SMTP email backend [/b]
In the example above,
Code:
EMAIL_BACKENDCode:
django.core.mail.backends.smtp.EmailBackendCode:
EmailBackendCode:
host: EMAIL_HOST
port: EMAIL_PORT
username: EMAIL_HOST_USER
password: EMAIL_HOST_PASSWORD
use_tls: EMAIL_USE_TLS
use_ssl: EMAIL_USE_SSLUnspecified arguments default to
Code:
NoneAs well as
Code:
.smtp.EmailBackend- – the console backend that composes the emails that will be sent to the standard output. Not intended for production use.Code:
django.core.mail.backends.console.EmailBackend
- – the file backend that creates emails in the form of a new file per each new session opened on the backend. Not intended for production use.Code:
django.core.mail.backends.filebased.EmailBackend
- – the in-memory backend that stores messages in the local memory cache ofCode:
django.core.mail.backends.locmem.EmailBackend. Not intended for production use.Code:django.core.mail.outbox
- – the dummy cache backend that implements the cache interface and does nothing with your emails. Not intended for production use.Code:
django.core.mail.backends.dummy.EmailBackend
- Any out-of-the-box backend for Amazon SES, Mailgun, SendGrid, and other services.
[b]How to send emails via SMTP [/b]
Once you have that configured, all you need to do to send an email is to import the
Code:
send_mailCode:
send_mass_mailfunctionCode:
django.core.mailCode:
send_mailusesCode:
send_mass_mailopens[b]Sending email with send_mail[/b]
This is the most basic function for email delivery in Django. It comprises four obligatory parameters to be specified:
Code:
subjectCode:
messageCode:
from_emailCode:
recipient_listIn addition to them, you can adjust the following:
- : IfCode:
auth_userhas not been specified, or you want to override it, this username will be used to authenticate to the SMTP server.Code:EMAIL_HOST_USER
- : IfCode:
auth_passwordhas not been specified, this password will be used to authenticate to the SMTP server.Code:EMAIL_HOST_PASSWORD
- : The optional email backend you can use without tweakingCode:
connection.Code:EMAIL_BACKEND
- : Lets you send multipart emails.Code:
html_message
- : A boolean that controls how the backend should handle errors. IfCode:
fail_silently– exceptions will be silently ignored. IfCode:True–Code:Falsewill be raised.Code:smtplib.SMTPException
For example, it may look like this:
Code:
from django.core.mail import send_mail
send_mail( subject = 'That’s your subject' message = 'That’s your message body' from_email = 'from@yourdjangoapp.com' recipient_list = ['to@yourbestuser.com',] auth_user = 'Login' auth_password = 'Password' fail_silently = False,
)Other functions for email delivery include
Code:
mail_adminsCode:
mail_managersFor them, you can specify such arguments as
Code:
subjectCode:
messageCode:
fail_silentlyCode:
connectionCode:
html_messageThe
Code:
from_emailCode:
SERVER_EMAIL[b]What is EmailMessage for? [/b]
If the email backend handles the email sending, the
Code:
EmailMessageCode:
EmailMessageCode:
from django.core.mail import EmailMessage
email = EmailMessage( subject = 'That’s your subject', body = 'That’s your message body', from_email = 'from@yourdjangoapp.com', to = ['to@yourbestuser.com'], bcc = ['bcc@anotherbestuser.com'], reply_to = ['whoever@itmaybe.com'],
)In addition to the
Code:
EmailMessage- : defines an email backend instance for multiple messages.Code:
connection
- : specifies the attachment for the message.Code:
attachments
- : specifies extra headers like Message-ID or CC for the message.Code:
headers
- : specifies email addresses used in the “CC” header.Code:
cc
The methods you can use with the
Code:
EmailMessage- : get the message sent.Code:
send
- : composes a MIME object (Code:
messageorCode:django.core.mail.SafeMIMEText).Code:django.core.mail.SafeMIMEMultipart
- : returns a list of the recipients specified in all the attributes including to, cc, and bcc.Code:
recipients
- : creates and adds a file attachment. It can be called with a MIMEBase instance or a triple of arguments consisting of filename, content, and mime type.Code:
attach
- : creates an attachment using a file from a filesystem. We’ll talk about adding attachments a bit later.Code:
attach_file
[b]How to send multiple emails[/b]
To deliver a message via SMTP, you need to open a connection and close it afterwards. This approach is quite awkward when you need to send multiple transactional emails. Instead, it is better to create one connection and reuse it for all messages.
This can be done with the
Code:
send_messagesCode:
from django.core import mail
connection = mail.get_connection()
connection.open()
email1 = mail.EmailMessage( 'That’s your subject', 'That’s your message body', 'from@yourdjangoapp.com', ['to@yourbestuser1.com'], connection=connection,
)
email1.send()
email2 = mail.EmailMessage( 'That’s your subject #2', 'That’s your message body #2', 'from@yourdjangoapp.com', ['to@yourbestuser2.com'],
)
email3 = mail.EmailMessage( 'That’s your subject #3', 'That’s your message body #3', 'from@yourdjangoapp.com', ['to@yourbestuser3.com'],
)
connection.send_messages([email2, email3])
connection.close()What you can see here is that the connection was opened for
Code:
email1Code:
send_messages[b]How to send multiple emails with send_mass_mail[/b]
Code:
send_mass_mailCode:
message1 = ('That’s your subject #1', 'That’s your message body #1', 'from@yourdjangoapp.com', ['to@yourbestuser1.com', 'to@yourbestuser2.com'])
message2 = ('That’s your subject #2', 'That’s your message body #2', 'from@yourdjangoapp.com', ['to@yourbestuser2.com'])
message3 = ('That’s your subject #3', 'That’s your message body #3', 'from@yourdjangoapp.com', ['to@yourbestuser3.com'])
send_mass_mail((message1, message2, message3), fail_silently=False)Each email message contains a datatuple made of
Code:
subjectCode:
messageCode:
from_emailCode:
recipient_listCode:
send_mail[b]How to send an HTML email[/b]
All versions starting from 1.7 let you send an email with HTML content using
Code:
send_mailCode:
from django.core.mail import send_mail
subject = 'That’s your subject'
html_message = render_to_string('mail_template.html', {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'from@yourdjangoapp.com>'
to = 'to@yourbestuser.com'
mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)Older versions users will have to mess about with
Code:
EmailMessageCode:
EmailMultiAlternativesCode:
attach_alternativeCode:
from django.core.mail import EmailMultiAlternatives
subject = 'That’s your subject'
from_email = 'from@yourdjangoapp.com>'
to = 'to@yourbestuser.com'
text_content = 'That’s your plain text.'
html_content = '<p>That’s <strong>the HTML part</strong></p>'
message = EmailMultiAlternatives(subject, text_content, from_email, [to])
message.attach_alternative(html_content, "text/html")
message.send()In the
Code:
EmailMessageCode:
attachCode:
attach_fileThe first one creates and adds a file attachment through three arguments – filename, content, and mime type.
The second method uses a file from a filesystem as an attachment. That’s how each method would look like in practice:
Code:
message.attach('Attachment.pdf', file_to_be_sent, 'file/pdf')or
Code:
message.attach_file('/documents/Attachment.pdf')You’re not limited to the abovementioned email backend options and can tailor your own. For this, you can use standard backends as a reference. Let’s say, you need to create a custom email backend with the
Code:
SMTP_SSLThe default SMTP backend will be the reference. First, add a new email option to settings.py.
Code:
AWS_ACCESS_KEY_ID = 'your-aws-access-key-id'
AWS_SECRET_ACCESS_KEY = 'your-aws-secret-access-key'
AWS_REGION = 'your-aws-region'
EMAIL_BACKEND = 'your_project_name.email_backend.SesEmailBackend'Make sure that you are allowed to send emails with Amazon SES using these
Code:
AWS_ACCESS_KEY_IDCode:
AWS_SECRET_ACCESS_KEYThen create a file your_project_name/email_backend.py with the following content:
Code:
import boto3
from django.core.mail.backends.smtp import EmailBackend
from django.conf import settings
class SesEmailBackend(EmailBackend): def __init__( self, fail_silently=False, **kwargs ): super().__init__(fail_silently=fail_silently) self.connection = boto3.client( 'ses', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, region_name=settings.AWS_REGION, ) def send_messages(self, email_messages): for email_message in email_messages: self.connection.send_raw_email( Source=email_message.from_email, Destinations=email_message.recipients(), RawMessage={"Data": email_message.message().as_bytes(linesep="\r\n")} )This is the minimum needed to send an email using SES. Surely you will need to add some error handling, input sanitization, retries etc. but this is out of our topic.
You might see that we have imported boto3 in the beginning of the file. Don’t forget to install it using a command
Code:
pip install boto3It’s not necessary to reinvent the wheel every time you need a custom email backend. You can find already existing libraries, or just receive SMTP credentials in your Amazon console and use the default email backend. It’s just about figuring out the best option for you and your project.
[b]Sending emails using SES from Amazon[/b]
So far, you can benefit from several services that allow you to send transactional emails at ease. If you can’t choose one, check out our blog post about Sendgrid vs. Mandrill vs. Mailgun. It will help a lot. At this point, Mailtrap has launched its own sending solution.
So, you could easily start sending transactional emails in Django using our guide. But today, we’ll discover how to make your Django app send emails via Amazon SES. It is one of the most popular services so far. Besides, you can take advantage of a ready-to-use Django email backend for this service – django-ses.
[b]Set up the library[/b]
You need to execute pip install django-ses to install django-ses. Once it’s done, tweak your settings.py with the following line:
Code:
EMAIL_BACKEND = 'django_ses.SESBackend'Don’t forget to set up your AWS account to get the required credentials – AWS access keys that consist of access key ID and secret access key.
For this, add a user in Identity and Access Management (IAM) service.
Then, choose a user name and Programmatic access type. Attach
Code:
AmazonSESFullAccessCode:
AWS_ACCESS_KEY_ID = '********'
AWS_SECRET_ACCESS_KEY = '********'Now, you can send your emails using
Code:
django.core.mail.send_mailCode:
from django.core.mail import send_mail
send_mail( 'That’s your subject', 'That’s your message body', 'from@yourdjangoapp.com', ['to@yourbestuser.com']
)Code:
django-ses[b]Testing email sending in Django [/b]
Once you’ve got everything prepared for sending email messages, it is necessary to do some initial testing of your mail server. In Python, this can be done with one command:
Code:
python -m smtpd -n -c DebuggingServer localhost:1025This allows you to send emails to your local SMTP server. The DebuggingServer feature won’t actually send the email but will let you see the content of your message in the shell window. That’s an option you can use off-hand.
[b]Django’s TestCase[/b]
TestCase is a solution to test a few aspects of your email delivery. It uses locmem.EmailBackend, which, as you remember, stores messages in the local memory cache – django.core.mail.outbox. So, this test runner does not actually send emails. Once you’ve selected this email backend
Code:
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'you can use the following unit test sample to test your email sending capability.
Code:
from django.core import mail
from django.test import TestCase
class EmailTest(TestCase): def test_send_email(self): mail.send_mail( 'That’s your subject', 'That’s your message body', 'from@yourdjangoapp.com', ['to@yourbestuser.com'], fail_silently=False, ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'That’s your subject') self.assertEqual(mail.outbox[0].body, 'That’s your message body')This code will test not only your email sending but also the correctness of the email subject and message body.
[b]Testing with Mailtrap[/b]
Mailtrap can be a rich solution for testing. First, it lets you test not only the SMTP server but also the email content and do other essential checks from the email testing checklist. Second, it is a rather easy-to-use tool.
All you need to do is to copy the SMTP credentials from your demo inbox and tweak your settings.py. Or you can just copy/paste these four lines from the Integrations section by choosing Django in the pop-up menu.
Code:
EMAIL_HOST = 'smtp.mailtrap.io'
EMAIL_HOST_USER = '********'
EMAIL_HOST_PASSWORD = '*******'
EMAIL_PORT = '2525'After that, feel free to send your HTML/CSS email with an attachment to check how it goes.
Code:
from django.core.mail import send_mail
subject = 'That’s your subject'
html_message = render_to_string('mail_template.html', {'context': 'values'}) plain_message = strip_tags(html_message)
from_email = 'from@yourdjangoapp.com>'
to = 'to@yourbestuser.com'
mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
message.attach('Attachment.pdf', file_to_be_sent, 'file/pdf')If there is no message in the Mailtrap Demo inbox or there are some issues with HTML content, you need to polish your code.
[b]Django email libraries to simplify your life[/b]
As a conclusion to this blog post about sending emails with Django, we’ve included a brief introduction of a few libraries that will facilitate your email workflow.
[b]django-anymail[/b]
This is a collection of email backends and webhooks for numerous famous email services including SendGrid, Mailgun, and others.
Code:
django-anymailCode:
django.core.mail[b]django-mailer[/b]
django-mailer is a Django app you can use to queue email sending. With it, scheduling your emails is much easier.
[b]django-post_office[/b]
With this app, you can send and manage your emails. django-post_office offers many cool features like asynchronous email sending, built-in scheduling, multiprocessing, etc.
[b]django-templated-email[/b]
This app is about sending templated emails. In addition to its own functionalities, django-templated-email can be used in tow with
Code:
django-anymail[b]How to receive emails in Django[/b]
To receive emails in Django, it is better to use the django-mailbox development library if you need to import messages from local mailboxes, POP3, IMAP, or directly receive messages from Postfix or Exim4.
While using Django-mailbox, mailbox functions as a message queue that is being gradually processed. The library helps retrieve email messages and then erases them so they are not downloaded again the next time.
Mailbox types supported by django-mailbox: POP3, IMAP, Gmail IMAP with Oauth2 authentication, local file-based mailboxes like Maildir, Mbox, Babyl, MH, or MMDF.
Here’s a step-by-step guide on how to quickly set up your Django-mailbox and start receiving emails.
[b]Installation[/b]
There are two ways to install django-mailbox:
1. From pip:
Code:
pip install django-mailbox2. From the github-repository:
Code:
git clone https://github.com/coddingtonbear/django-mailbox.git
cd django-mailbox
python setup.py install- After installing the package, go to settings.py file of the django project and add toCode:
django_mailbox.Code:INSTALLED_APPS
- Then, run python from your project file to create the necessary database tables.Code:
manage.py migrate django_mailbox
- Finally, go to your project’s Django Admin and create a mailbox to consume.
- Don’t forget to verify if your mailbox was set up right. You can do that from a shell opened to your project’s directory, using the command runningCode:
getmailCode:python manage.py getmail
When you are done with the installation and checking the configurations, it’s time to receive incoming emails. There are five different ways to do that.
- In your code
Use the
Code:
get_new_mail- With Django Admin
Go to Django Admin, then to ‘Mailboxes’ page, check all the mailboxes you need to receive emails from. At the top of the list with mailboxes, choose the action selector ‘Get new mail’ and click ‘Go’.
- With cron job
Run the management command
Code:
getmailCode:
python manage.py getmail- Directly from Exim4
To configure Exim4 to receive incoming mail begin with adding a new router:
Code:
django_mailbox: debug_print = 'R: django_mailbox for $localpart@$domain' driver = accept transport = send_to_django_mailbox domains = mydomain.com local_parts = emailusernameone : emailusernametwoIn case the email addresses you are trying to add are handled by other routers, disable them. For this change, the contents of
Code:
local_parts5. Directly from Postfix
With Postfix get new mail to a script using
Code:
pipeThere’s also an option to subscribe to the incoming
Code:
django-mailboxUse this piece of code to do that:
Code:
from django_mailbox.signals import message_received
from django.dispatch import receiver @receiver(message_received)
def dance_jig(sender, message, **args): print "I just received a message titled %s from a mailbox named %s" % (message.subject, message.mailbox.name, )Keep in mind that this should be loaded to models.py or elsewhere early enough for the signal not to be fired before your signal handler’s registration is processed.
We hope that you find our guide helpful and the list of packages covered help facilitate your email workflow. You can always find more apps at Django Packages.
This article was originally published on Mailtrap’s blog: Sending emails in Django with code examples. We have repurposed it on the Finxter blog with their permission!

