Sending emails in most of the apps we interact with is an important aspect, that has almost become naturalized. For developers like you and me it is a feature that we almost always have to implement and the languages or frameworks we write apps in, give us a way of sending emails and Django is no exception, it makes it so easy to send emails by providing wrappers over the smtplib Python library.
However for Django to be able to send out emails it needs to connect to an smtp host and that is where SendGrid comes in.To use SendGrid as your smtp host you need to register with them here, once you have created an account then go to settings and create an API key. You should see something like in the image below.
I will not delve much into the key creation it is an easy one really. Having said that we need to configure our Django application to work with environment variables since it does not have that configured out of the box.To do so we need to install a small dependency that will help us read values off the envrinoment variables file or the .env as is it commonly known. So first we will install django-environ. Read more about it here
pip install django-environ
After the install is done then create a .env file in the root of your app, then create a SendGrid environment variable see example below, you can name it whatever you like but it is good to use descriptive names for the same.
Once that is done the next thing that you want to do is put the following settings in the settings.py file of your project, it is worth noting that there will be other settings in the file so you will just add the below imports and settings accordingly
import environ # add this import # add this line before the BASE_DIR setting env = environ.Env(DEBUG=(bool, True)) # add this line after the BASE_DIR setting environ.Env.read_env(os.path.join(BASE_DIR, '.env')) # finally you can place this settings at the bottom of the file EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = env('SENDGRID_API_KEY') EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = env('FROM_EMAIL', default='just_put_your_email_address')
Now that we have got the settings out of the way, the next thing we want to do is install a sendgrid like below.
pip install sendgrid
With everything setup we have two options of sending emails now we can use the Django send_mail function see the docs for more here or we can use the SendGrid Mail constructor.It is worth noting that the django.core.mail is quite sufficient. I just prefer the sendgrid option and that is what I will show you the example next. So we will create an email module and create an email sending function and then import it whenever we to send an email.So create an email_handler.py file and put the following code in it.
from <yourproject>.settings import env from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail def send_email(receiver_email, the_subject, the_content): """send email on relevant user action""" message = Mail( from_email=(env('FROM_EMAIL'), "Title of the sender"), to_emails=receiver_email, subject=the_subject, html_content=the_content, ) try: sg = SendGridAPIClient(env("SENDGRID_API_KEY")) sg.send(message) except Exception as e: # don't print errors log them print(e)
Lets start with the imports the first one is an import for env which is just a variable that we have initialized in the settings.py file above.
The next two imports are from sendgrid which we had installed earlier. The first one allows us to pass our api key to sendgrid for authorization and the next one allows us to import Mail constructor which will initialize a mail object. Basically the sender email, the email subject, receiver email, and finally the message which can be plain text string or html content.
The we define a function to send mail that we will be calling every time we want to send an email in our code, Note you can define a class for the same or you can define a function like I did it really is just a matter of preference really. The function takes the following arguments receiver_email, the_subject, the_content all of which are strings. Then finally is a try except block which is just for I mean try and send the email as constructed above and if it fails for whatever reason log that error for the site admin.
So when we want to send an email anywhere in our code we just import the send_mail function from the email_handler module
and supply it with the above arguments like below
from <yourapp>.email_handler import send_mail send_mail("firstname.lastname@example.org", "Welcome to our site", "Thank you for signing up.")
Thank you and happy email sending.
Top comments (0)