🔍 Code Extractor

function get_email_templates

Maturity: 48

Loads HTML email templates from a predefined directory structure and returns them as a dictionary mapping template names to their content.

File:
/tf/active/vicechatdev/CDocs/utils/notifications.py
Lines:
387 - 407
Complexity:
simple

Purpose

This function scans the '../templates/email' directory relative to the current file location, reads all HTML files, and creates a dictionary where keys are template names (filenames without extension) and values are the template content. It handles missing directories gracefully and logs errors for individual template loading failures. This is typically used in email notification systems to load reusable email templates for various communication purposes.

Source Code

def get_email_templates():
    """Load email templates from template directory."""
    templates = {}
    template_dir = os.path.join(os.path.dirname(__file__), '../templates/email')
    
    if not os.path.exists(template_dir):
        logger.warning(f"Email template directory not found: {template_dir}")
        return templates
        
    for filename in os.listdir(template_dir):
        if not filename.endswith('.html'):
            continue
            
        template_name = os.path.splitext(filename)[0]
        try:
            with open(os.path.join(template_dir, filename), 'r', encoding='utf-8') as f:
                templates[template_name] = f.read()
        except Exception as e:
            logger.error(f"Error loading email template {filename}: {e}")
            
    return templates

Return Value

Returns a dictionary (Dict[str, str]) where keys are template names (derived from HTML filenames without the .html extension) and values are the complete HTML content of each template as strings. Returns an empty dictionary if the template directory doesn't exist or if no valid HTML templates are found.

Dependencies

  • os
  • logging

Required Imports

import os
import logging

Usage Example

import os
import logging

# Setup logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
logger.addHandler(handler)

# Call the function
templates = get_email_templates()

# Access loaded templates
if 'welcome' in templates:
    welcome_html = templates['welcome']
    print(f"Welcome template loaded: {len(welcome_html)} characters")

# Use template for email
if 'notification' in templates:
    email_body = templates['notification'].replace('{{user_name}}', 'John Doe')
    # Send email with email_body...

Best Practices

  • Ensure the logger object is properly initialized in the module before calling this function
  • Create the '../templates/email' directory structure relative to the file containing this function
  • Store only .html files in the template directory to avoid processing non-template files
  • Use UTF-8 encoding for all template files to ensure proper character handling
  • Template names should be unique as they become dictionary keys (duplicate filenames will overwrite)
  • Consider caching the returned templates dictionary to avoid repeated file I/O operations
  • Handle the case where the returned dictionary is empty (no templates found)
  • Template files should use consistent naming conventions (e.g., snake_case) for easier reference
  • Monitor logs for warnings about missing directories or errors loading specific templates

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function main_v43 58.8% similar

    A test function that validates email template rendering by testing multiple HTML email templates with sample data structures for document review and approval workflows.

    From: /tf/active/vicechatdev/test_comprehensive_templates.py
  • function gen_send_email 54.9% similar

    Sends templated emails using either MS365 or SMTP provider, with support for multiple recipients, attachments, and HTML/text rendering.

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function load_email_dates 52.8% similar

    Reads a CSV file (DOWNLOAD_REGISTER) containing email metadata and extracts filename-to-date mappings, parsing dates in YYYY-MM-DD format.

    From: /tf/active/vicechatdev/mailsearch/copy_signed_documents.py
  • function send_email 52.3% similar

    Sends templated emails to one or more recipients using either MS365 or SMTP provider based on configuration, with support for CC, BCC, and attachments.

    From: /tf/active/vicechatdev/CDocs single class/utils/notifications.py
  • function test_fixes 51.6% similar

    A comprehensive test function that validates email template rendering and CDocs application link presence in a document management system's email notification templates.

    From: /tf/active/vicechatdev/test_comprehensive_fixes.py
← Back to Browse