DEV Community

Mansuur Abdullahi Abdirahman
Mansuur Abdullahi Abdirahman

Posted on

How to send email in Django

To send an email in Django, we need to simple steps

Step 1:

Open settings.py and put the code below somewhere in your file

# Email sending configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'your-smtp-server.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "email_sender@gmail.com"
EMAIL_HOST_PASSWORD = "email_password"
Enter fullscreen mode Exit fullscreen mode

Step 2:

Once you done those configurations, now you we can perform sending email

// Import those packages
from django.core.mail import send_mail
from django.conf import settings
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
import smtplib
import ssl


// function that handles sending your email
def SendEmail(email_subject, email_message, email_reciever):
    sender_email = settings.EMAIL_HOST_USER  # Set the sender's email address
    receiver_email = email_reciever  # Set the recipient's email address
    password = settings.EMAIL_HOST_PASSWORD  # Set the password for the sender's email account

    message = MIMEMultipart("alternative")  # Create a MIME multipart message
    message["Subject"] = email_subject  # Set the email subject
    message["From"] = sender_email  # Set the sender of the email
    message["To"] = receiver_email  # Set the recipient of the email

    # Create the plain-text and HTML version of the email message
    text = email_message

    # Turn the plain-text version into a plain MIMEText object
    part1 = MIMEText(text, "plain")

    # Add the plain-text part to the MIMEMultipart message
    # The email client will try to render the last part first
    message.attach(part1)

    try:
        # Create a secure connection with the email server and send the email
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
            server.login(sender_email, password)  # Log in to the email server
            server.sendmail(
                sender_email, receiver_email, message.as_string()
            )  # Send the email
    except Exception as error:
        print('Exception Occurred', error)  # Print any exceptions that occur during the process
Enter fullscreen mode Exit fullscreen mode

Step 3:

This is how we can use it

subject = "Hello from Assistant"
message = "This is a test email sent using the SendEmail function."
receiver = "example@example.com"

SendEmail(subject, message, receiver)
Enter fullscreen mode Exit fullscreen mode

This is how we can send an email using Django

Top comments (0)