function test_smtp_connection
Tests the SMTP connection to a local email forwarder service running on port 2525 by establishing a connection and performing an EHLO handshake.
/tf/active/vicechatdev/email-forwarder/test_e2e.py
12 - 24
simple
Purpose
This function is designed to verify that an SMTP server (specifically an email forwarder service) is running and accessible on localhost port 2525. It performs a basic connectivity test and EHLO command to confirm the server is responding correctly. This is typically used for health checks, integration tests, or debugging email forwarding functionality.
Source Code
def test_smtp_connection():
"""Test SMTP connection to the forwarder service."""
try:
print("Testing SMTP connection...")
with smtplib.SMTP('127.0.0.1', 2525, timeout=10) as server:
print("✓ Successfully connected to SMTP server")
# Try to get server info
code, msg = server.ehlo()
print(f"✓ EHLO response: {code} - {msg.decode()}")
return True
except Exception as e:
print(f"✗ SMTP connection failed: {e}")
return False
Return Value
Returns a boolean value: True if the SMTP connection is successfully established and the EHLO handshake completes without errors, False if any exception occurs during the connection attempt or handshake. The function also prints status messages to stdout indicating success or failure details.
Dependencies
smtplib
Required Imports
import smtplib
Usage Example
import smtplib
def test_smtp_connection():
"""Test SMTP connection to the forwarder service."""
try:
print("Testing SMTP connection...")
with smtplib.SMTP('127.0.0.1', 2525, timeout=10) as server:
print("✓ Successfully connected to SMTP server")
code, msg = server.ehlo()
print(f"✓ EHLO response: {code} - {msg.decode()}")
return True
except Exception as e:
print(f"✗ SMTP connection failed: {e}")
return False
# Usage
if __name__ == '__main__':
connection_status = test_smtp_connection()
if connection_status:
print("SMTP server is ready")
else:
print("SMTP server is not available")
Best Practices
- Ensure the SMTP forwarder service is running before calling this function
- The function uses a 10-second timeout to prevent hanging on connection attempts
- This function prints output directly to stdout, so it's best suited for CLI tools or test scripts rather than library code
- The function catches all exceptions broadly, which is appropriate for a test function but may hide specific error details
- Consider wrapping this in a retry loop for more robust testing in CI/CD environments
- The hardcoded IP (127.0.0.1) and port (2525) make this function specific to local testing; consider parameterizing these values for more flexible usage
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_smtp_basic 90.5% similar
-
function send_test_email_v1 84.7% similar
-
function send_test_email 76.4% similar
-
function check_port_listening 74.0% similar
-
function main_v57 71.3% similar