🔍 Code Extractor

function send_email_smtp

Maturity: 78

Sends emails via SMTP server with support for HTML/text content, multiple recipients (to/cc/bcc), and file attachments.

File:
/tf/active/vicechatdev/CDocs/utils/notifications.py
Lines:
545 - 611
Complexity:
moderate

Purpose

This function provides a comprehensive email sending capability through SMTP protocol. It handles multipart MIME messages with both HTML and plain text alternatives, supports multiple recipient types (to, cc, bcc), allows file attachments, and includes TLS encryption and authentication. It's designed for applications that need to send formatted emails with optional attachments through a configured SMTP server, with error handling that returns a boolean success indicator.

Source Code

def send_email_smtp(to_addresses: List[str], 
                   subject: str, 
                   body_html: str, 
                   body_text: str = None,
                   cc_addresses: List[str] = None,
                   bcc_addresses: List[str] = None,
                   attachments: List[Dict[str, Any]] = None) -> bool:
    """
    Send email through SMTP server.
    
    Args:
        to_addresses: List of recipient email addresses
        subject: Email subject
        body_html: HTML body content
        body_text: Optional plain text body
        cc_addresses: Optional list of CC recipients
        bcc_addresses: Optional list of BCC recipients
        attachments: Optional list of attachments as dictionaries with keys:
                    'filename', 'content' (bytes), 'content_type'
                    
    Returns:
        Boolean indicating success
    """
    try:
        # Create message
        msg = MIMEMultipart('alternative')
        msg['From'] = settings.EMAIL_SENDER
        msg['To'] = ', '.join(to_addresses)
        msg['Subject'] = subject
        
        # Add CC if provided
        if cc_addresses:
            msg['Cc'] = ', '.join(cc_addresses)
            
        # Add text and HTML parts
        if body_text:
            msg.attach(MIMEText(body_text, 'plain'))
        msg.attach(MIMEText(body_html, 'html'))
        
        # Add attachments if provided
        if attachments:
            for attachment in attachments:
                part = MIMEApplication(attachment['content'])
                part.add_header('Content-Disposition', 'attachment', 
                               filename=attachment['filename'])
                msg.attach(part)
        
        # Get all recipients
        all_recipients = to_addresses.copy()
        if cc_addresses:
            all_recipients.extend(cc_addresses)
        if bcc_addresses:
            all_recipients.extend(bcc_addresses)
        
        # Connect to SMTP server
        with smtplib.SMTP(settings.SMTP_SERVER, settings.SMTP_PORT) as server:
            if settings.SMTP_USE_TLS:
                server.starttls()
            if settings.SMTP_USERNAME and settings.SMTP_PASSWORD:
                server.login(settings.SMTP_USERNAME, settings.SMTP_PASSWORD)
            server.send_message(msg, from_addr=settings.EMAIL_SENDER, to_addrs=all_recipients)
            
        return True
        
    except Exception as e:
        logger.error(f"Error sending email through SMTP: {e}")
        return False

Parameters

Name Type Default Kind
to_addresses List[str] - positional_or_keyword
subject str - positional_or_keyword
body_html str - positional_or_keyword
body_text str None positional_or_keyword
cc_addresses List[str] None positional_or_keyword
bcc_addresses List[str] None positional_or_keyword
attachments List[Dict[str, Any]] None positional_or_keyword

Parameter Details

to_addresses: List of primary recipient email addresses (strings). Must contain at least one valid email address. These recipients will be visible in the 'To' field of the email.

subject: String containing the email subject line. Can be any text, will appear in the email header.

body_html: String containing the HTML-formatted email body. This is the primary content and will be displayed by email clients that support HTML rendering.

body_text: Optional string containing plain text version of the email body. If provided, creates a multipart/alternative message allowing email clients to choose between HTML and plain text. Defaults to None.

cc_addresses: Optional list of email addresses to receive carbon copies. These recipients will be visible to all other recipients. Defaults to None.

bcc_addresses: Optional list of email addresses to receive blind carbon copies. These recipients will not be visible to other recipients. Defaults to None.

attachments: Optional list of dictionaries, where each dictionary represents a file attachment with keys: 'filename' (string, name of file), 'content' (bytes, file content), and 'content_type' (string, MIME type, though currently not used in implementation). Defaults to None.

Return Value

Type: bool

Returns a boolean value: True if the email was successfully sent through the SMTP server, False if any exception occurred during the process (connection failure, authentication error, invalid recipients, etc.). The function logs errors but does not raise exceptions.

Dependencies

  • smtplib
  • email.mime.multipart
  • email.mime.text
  • email.mime.application
  • logging
  • typing

Required Imports

from typing import List, Dict, Any
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import smtplib
import logging

Usage Example

# Configure settings (typically in config.py or settings module)
class Settings:
    EMAIL_SENDER = 'noreply@example.com'
    SMTP_SERVER = 'smtp.gmail.com'
    SMTP_PORT = 587
    SMTP_USE_TLS = True
    SMTP_USERNAME = 'your-email@gmail.com'
    SMTP_PASSWORD = 'your-app-password'

settings = Settings()

# Configure logger
import logging
logger = logging.getLogger(__name__)

# Basic email with HTML content
success = send_email_smtp(
    to_addresses=['recipient@example.com'],
    subject='Welcome to Our Service',
    body_html='<h1>Welcome!</h1><p>Thank you for joining us.</p>'
)

# Email with text alternative, CC, and attachment
with open('report.pdf', 'rb') as f:
    pdf_content = f.read()

success = send_email_smtp(
    to_addresses=['user@example.com'],
    subject='Monthly Report',
    body_html='<p>Please find attached your monthly report.</p>',
    body_text='Please find attached your monthly report.',
    cc_addresses=['manager@example.com'],
    bcc_addresses=['archive@example.com'],
    attachments=[{
        'filename': 'report.pdf',
        'content': pdf_content,
        'content_type': 'application/pdf'
    }]
)

if success:
    print('Email sent successfully')
else:
    print('Failed to send email')

Best Practices

  • Always configure SMTP_USE_TLS as True when connecting to modern SMTP servers to ensure encrypted communication
  • Use app-specific passwords rather than account passwords when authenticating with services like Gmail
  • Validate email addresses before passing them to this function to avoid SMTP errors
  • Keep attachment sizes reasonable (typically under 10-25MB) as many email servers have size limits
  • Always provide both body_html and body_text for better email client compatibility
  • Handle the boolean return value to implement retry logic or user notifications on failure
  • Ensure the settings object is properly configured before calling this function
  • Consider rate limiting when sending bulk emails to avoid being flagged as spam
  • The 'content_type' key in attachments dictionary is currently not used in the implementation; attachments are sent as application/octet-stream
  • BCC recipients are not added to message headers but are included in the SMTP envelope, maintaining their privacy

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function gen_send_email 76.6% 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 send_email_ms365 72.8% similar

    Sends an email through Microsoft 365 Graph API with support for HTML content, multiple recipients (to/cc/bcc), and file attachments.

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function send_test_email 66.4% similar

    Sends a test email via SMTP to verify email forwarding service functionality, creating a MIME multipart message with customizable sender, recipient, subject, and body content.

    From: /tf/active/vicechatdev/email-forwarder/send_test_email.py
  • function send_test_email_v1 56.7% similar

    Sends a test email to a local SMTP server (127.0.0.1:2525) to verify email forwarding functionality and service connectivity.

    From: /tf/active/vicechatdev/email-forwarder/test_e2e.py
  • function main_v69 52.6% similar

    Command-line interface function that parses arguments and sends a test email through an SMTP forwarder service, displaying connection details and returning an exit code based on success.

    From: /tf/active/vicechatdev/email-forwarder/send_test_email.py
← Back to Browse