Skip to content
thesarfo

Note

Sending Emails

Running a local SMTP4dev server for dev email testing, the available Django email backends, and using send_mail/mail_admins.

views 0

If we want to send emails in our dev environment we have to use smtp to do that. If you go to the github of SMTP4DEV you will find instructions on how to run a fake smtp server with docker. After we install docker and we download the smtp server and it is running, we can now start sending emails.

It also provides us with an admin panel at localhost:3000 for us to see what emails we have sent.

Email Backends.

Django provides us a lot of email backends. They are below

  1. SMTP (default)
  2. Console
  3. File
  4. Locmem
  5. Dummy

To set up the email backend in django, you need to specify some settings in your settings.py file..

EMAIL_BACKENDS = 'django.core.mail.backends.smtp.EmailBackend' # change from smtp to other
EMAIL_HOST = 'localhost' # we are hosting on localhost since it is local
EMAIL_HOST_USER = '' # by default we dont have a username and a password
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 2525 # smtp runs on port 25 but since its a fake smtp server it runs on port 2525
DEFAULT_FROM_EMAIL = 'from@thesarfo.com' # the email that will send

To actually send an email you need to define some functions in your code. Navigate to a dummy app where you wanna set this email function up and see below.

from django.shortcuts import render
from django.core.mail import send_mail, mail_admins, BadHeaderError
def say_hello(request):
try:
mail_admins('subject', 'message', html_message='message')
send_mail('subject', 'message', 'info@thesarfo.com', ['someone@example.com'])
except BadHeaderError:
pass
return render(request, 'hello.html', {'name': 'Ernest'})

The send_mail is used to send an email to a person. it takes some args. subject of the email, the email message, the acc to send the email(this overrides the from_email in the settings.py), and the email you wanna send the message to(this is a list of emails). Now when you trigger this function by hitting the endpoint associated with it, you will see in your smtp4dev that an email has been send.

Note how we have a mail_admins too…that one is for sending emails to a site admins. It takes 3 arguments. the subject of the email, the message of the email, and the html_message you want to send(we have just sent message in this case). Now to finish configuring the mail_admins, you have to set a list of admins in your settings.py. It will be a list of tuples. see below

ADMINS = [
('Admin', 'admin@test.com')
]

Trigger the function by hitting the endpoint and your smtp4dev will show that an email has been sent.

The BadHeaderError is simply to protect our email sending from attackers who may try to mimick us. So we throw an exception in that case