SMTP - Send Emails in Python
You can use any SMTP server with minor modifications, but this document is written specifically with Gmail in mind.
Prerequisites
- A Gmail account with or without 2FA
Steps
1. Prepare an App Password
If your Gmail account uses 2FA (two factor or two party authentication), then you must set up an app password to authenticate from Python.
If your Gmail account does not use 2FA, you should be able to just use your Gmail and password to authenticate from Python, but this hasn't been tested.
- Login to your Gmail account.
- Go to this URL and create an App Password.
- Make note of this password as you can't view it again after leaving the page.
2. Configure Django Settings
If using Django, you should configure the following variables in the settings.py file:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', 'your_email@gmail.com')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
Ensure that you have a .env file in your root directory (same level as manage.py)
and that you include the following code near the top of your settings.py file:
from dotenv import load_dotenv
load_dotenv() # take environment variables from .env.
3. Send Emails
Adapt the following code snippet to send emails:
import smtplib
# Only import django settings if you're using django
from django.conf import settings
# Prepare the smtp server object:
server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
# Start TLS:
server.starttls()
# Login to the server with your credentials:
server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
# Send your email message:
server.sendmail(settings.EMAIL_HOST_USER, 'to_email@domain.com', 'Message body!')