🔍 Code Extractor

function send_test_email

Maturity: 46

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.

File:
/tf/active/vicechatdev/email-forwarder/send_test_email.py
Lines:
12 - 38
Complexity:
simple

Purpose

This function is designed for testing SMTP email forwarding services by sending a simple test email. It's particularly useful for validating email server configurations, testing email relay services, or verifying that an SMTP forwarder is operational. The function provides console feedback about connection status and delivery success, making it ideal for debugging and integration testing scenarios.

Source Code

def send_test_email(smtp_host='localhost', smtp_port=2525, 
                   sender='test@example.com', recipient='recipient@example.com',
                   subject='Test Email', message='This is a test email.'):
    """Send a test email to the forwarder service."""
    
    print(f"Connecting to SMTP server at {smtp_host}:{smtp_port}")
    
    try:
        # Create message
        msg = MIMEMultipart()
        msg['From'] = sender
        msg['To'] = recipient
        msg['Subject'] = subject
        
        # Add body
        msg.attach(MIMEText(message, 'plain'))
        
        # Connect and send
        with smtplib.SMTP(smtp_host, smtp_port) as server:
            print("Connected to SMTP server")
            server.send_message(msg)
            print(f"✓ Email sent successfully from {sender} to {recipient}")
            return True
            
    except Exception as e:
        print(f"✗ Failed to send email: {e}")
        return False

Parameters

Name Type Default Kind
smtp_host - 'localhost' positional_or_keyword
smtp_port - 2525 positional_or_keyword
sender - 'test@example.com' positional_or_keyword
recipient - 'recipient@example.com' positional_or_keyword
subject - 'Test Email' positional_or_keyword
message - 'This is a test email.' positional_or_keyword

Parameter Details

smtp_host: The hostname or IP address of the SMTP server to connect to. Defaults to 'localhost' for local testing. Can be any valid hostname or IP address string.

smtp_port: The port number on which the SMTP server is listening. Defaults to 2525, a common non-privileged port for testing. Standard SMTP ports are 25 (unencrypted), 587 (STARTTLS), or 465 (SSL/TLS). Must be an integer between 1-65535.

sender: The email address that will appear in the 'From' field of the email. Defaults to 'test@example.com'. Should be a valid email address format string.

recipient: The email address that will receive the test email. Defaults to 'recipient@example.com'. Should be a valid email address format string.

subject: The subject line text for the test email. Defaults to 'Test Email'. Can be any string value.

message: The plain text body content of the email. Defaults to 'This is a test email.' Can be any string value, will be sent as plain text MIME type.

Return Value

Returns a boolean value: True if the email was successfully sent through the SMTP server without exceptions, False if any exception occurred during the connection or sending process. The function also prints status messages to console indicating success or failure details.

Dependencies

  • smtplib
  • email.mime.text
  • email.mime.multipart

Required Imports

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

Usage Example

# Basic usage with defaults (localhost SMTP server on port 2525)
result = send_test_email()

# Custom SMTP server and credentials
result = send_test_email(
    smtp_host='mail.example.com',
    smtp_port=587,
    sender='noreply@mycompany.com',
    recipient='admin@mycompany.com',
    subject='Production Test',
    message='Testing email forwarding in production environment.'
)

if result:
    print('Email delivery confirmed')
else:
    print('Email delivery failed')

# Testing local development SMTP server
result = send_test_email(
    smtp_host='127.0.0.1',
    smtp_port=1025,
    sender='dev@localhost',
    recipient='test@localhost'
)

Best Practices

  • This function does not support SMTP authentication (username/password). For production use with authenticated SMTP servers, extend the function to include server.login() before sending.
  • The function uses plain SMTP without TLS/SSL encryption. For secure email transmission, consider using smtplib.SMTP_SSL or calling server.starttls() after connection.
  • Error handling catches all exceptions generically. For production use, consider catching specific exceptions (smtplib.SMTPException, socket.error) for better error reporting.
  • The function prints directly to console. For library use, consider using logging module or returning error messages instead of printing.
  • Default port 2525 is non-standard and typically used for testing. Production SMTP typically uses port 25, 587, or 465.
  • The function creates a MIMEMultipart message but only attaches plain text. This structure allows for easy extension to include HTML content or attachments.
  • No timeout is specified for the SMTP connection. Consider adding a timeout parameter for better control in network-constrained environments.
  • The sender and recipient addresses are not validated. Consider adding email format validation before attempting to send.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function send_test_email_v1 87.9% 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 test_smtp_connection 76.4% similar

    Tests the SMTP connection to a local email forwarder service running on port 2525 by establishing a connection and performing an EHLO handshake.

    From: /tf/active/vicechatdev/email-forwarder/test_e2e.py
  • function main_v69 74.8% 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
  • function test_send_email 74.5% similar

    Interactive test function that prompts the user to send a test email through the O365Client to verify email sending functionality.

    From: /tf/active/vicechatdev/email-forwarder/test_service.py
  • class TestSmtpServer 70.0% similar

    A test class for validating the functionality of the SmtpServer class, including server startup, email handling, email forwarding, and error handling for invalid inputs.

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