You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

发送错误邮箱时如何获取SMTP连接状态日志?代码调整求助

How to Capture Connection Status & Failed Delivery Logs with smtplib

Let's break down how to get exactly what you need: clean connection status logs, plus clear feedback when sending to an invalid email address.

First, Fix Variable Name Inconsistencies

Looking at your code, there are some mismatched variable names (e.g., from_mail instead of from_email, to_mail instead of to_email). These typos can cause unexpected errors, so let's correct those first.

Capture Connection Status Logs Cleanly

The set_debuglevel(1) method does output connection details, but it dumps all SMTP communication to stdout by default. To capture only the connection-related logs without cluttering the console, we can redirect this output to a buffer and extract relevant lines:

import smtplib
from io import StringIO
import sys

# Configuration (fix variable names here)
mailserver = "your-mail-server.com"
to_email = "wrong-address@example.com"
from_email = "your-address@example.com"
subject = "Test Subject"
message = """From: {from_email}
To: {to_email}
Subject: {subject}

This is a test message.
""".format(from_email=from_email, to_email=to_email, subject=subject)

# Capture debug output to a buffer
debug_buffer = StringIO()
original_stdout = sys.stdout
sys.stdout = debug_buffer

try:
    # Initialize SMTP server and enable debug mode
    server = smtplib.SMTP(mailserver)
    server.set_debuglevel(1)
    
    # Connect and send email
    server.sendmail(from_email, to_email, message)
    
    # Extract connection-related logs
    sys.stdout = original_stdout
    debug_output = debug_buffer.getvalue()
    connection_logs = [line for line in debug_output.splitlines() if any(keyword in line for keyword in ["connect", "220", "EHLO", "250", "QUIT", "221"])]
    
    print("=== Connection Status Logs ===")
    for line in connection_logs:
        print(line)
        
except smtplib.SMTPException as e:
    sys.stdout = original_stdout
    print(f"SMTP Error occurred: {str(e)}")
finally:
    server.quit()

Detect Invalid Email Addresses

Your second approach using mail_response = server.sendmail(...) is actually correct for capturing delivery failures! The sendmail method returns a dictionary where keys are the failed recipient addresses, and values are tuples of (error_code, error_message). If the email address is invalid, it will show up here.

Let's combine this with the connection logs for a complete solution:

import smtplib
from io import StringIO
import sys

# Configuration
mailserver = "your-mail-server.com"
to_email = "wrong-address@example.com"
from_email = "your-address@example.com"
subject = "Test Subject"
message = """From: {from_email}
To: {to_email}
Subject: {subject}

This is a test message.
""".format(from_email=from_email, to_email=to_email, subject=subject)

# Capture debug output
debug_buffer = StringIO()
original_stdout = sys.stdout
sys.stdout = debug_buffer

try:
    server = smtplib.SMTP(mailserver)
    server.set_debuglevel(1)
    
    # Get delivery status
    delivery_status = server.sendmail(from_email, to_email, message)
    
    # Restore stdout and process logs
    sys.stdout = original_stdout
    debug_output = debug_buffer.getvalue()
    connection_logs = [line for line in debug_output.splitlines() if any(keyword in line for keyword in ["connect", "220", "EHLO", "250", "QUIT", "221"])]
    
    print("=== Connection Status Logs ===")
    for line in connection_logs:
        print(line)
        
    print("\n=== Delivery Status ===")
    if not delivery_status:
        print("All emails sent successfully!")
    else:
        for addr, error in delivery_status.items():
            print(f"Failed to send to {addr}: Error {error[0]} - {error[1]}")
            
except smtplib.SMTPException as e:
    sys.stdout = original_stdout
    print(f"SMTP Error occurred: {str(e)}")
finally:
    server.quit()

Key Notes:

  • Connection Logs: The filtered lines will show you if the server connected successfully, responded to EHLO, accepted the message, and closed the connection properly.
  • Delivery Status: The delivery_status dict will explicitly tell you which addresses failed and why (e.g., invalid address, mailbox full, etc.).
  • Error Handling: The try-except block catches general SMTP errors (like unable to connect to the server) that might not be captured by sendmail's return value.

This way, you get exactly the connection status logs you need, plus clear feedback on any invalid email addresses you tried to send to.

内容的提问来源于stack exchange,提问作者shinobu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 22:32:29