Django Email Notification Sender

  • Share this:

Code introduction


This function utilizes Django's email sending capabilities and template rendering to send a notification email to a specified user.


Technology Stack : Django, Django.core.mail, Django.template.loader

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from django.core.mail import send_mail
from django.template.loader import render_to_string

def send_notification_email(user_email, user_name, subject, message):
    """
    This function sends a notification email to a user.
    """
    # Render the email template with the user's information
    email_template = render_to_string('emails/notification_email.html', {
        'user_name': user_name,
        'subject': subject,
        'message': message
    })
    
    # Send the email
    send_mail(
        subject,
        '',
        'from@example.com',
        [user_email],
        fail_silently=False,
        html_message=email_template
    )