我正在尝试创建一个程序来读取未读电子邮件并使用自动回复来响应发送,自动回复将由使用某些短语触发。我正在 Mac OSX 中的 Visual Code 中执行此操作。我能够连接到 IMAP 和 SMTP,但随后出现以下错误, smtplib.SMTPServerDisconnected:请先运行 connect() 。
我尝试使用 smtplib 中的异常,如果 SMTP 服务器断开连接,应该引发该异常,但它没有执行任何操作。
def smtp_init():
print("Initializing STMP . . .",end = '')
global s
s = smtplib.SMTP(smtpserver,smtpserverport)
status_code = s.starttls()[0]
if status_code is not 220:
raise Exception('Starting tls failed: '+ str(status_code))
status_code = s.login(radr,pwd)[0]
if status_code is not 235:
raise Exception('SMTP login failed: '+ str(status_code))
print("Done. ")
except smtplib.SMTPServerDisconnected:
smtp_init()
continue
预期的结果是让程序循环检查电子邮件并回复它们(如果它们有与自动回复相对应的短语)。
import smtplib
import imaplib
# Email credentials and server details
SMTP_SERVER = 'smtp.example.com'
SMTP_PORT = 587
EMAIL_ADDRESS = '[email protected]'
EMAIL_PASSWORD = 'your-password'
def initialize_smtp_connection():
"""Initializes the SMTP connection with TLS and logs in to the server."""
global smtp_session
print("Establishing SMTP connection...", end='')
try:
smtp_session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
smtp_session.ehlo() # Greet the server
tls_status = smtp_session.starttls()[0]
if tls_status != 220:
raise ConnectionError(f'TLS handshake failed with status code: {tls_status}')
login_status = smtp_session.login(EMAIL_ADDRESS, EMAIL_PASSWORD)[0]
if login_status != 235:
raise ConnectionError(f'SMTP login failed with status code: {login_status}')
print("Connection successful.")
except smtplib.SMTPServerDisconnected:
print("SMTP server disconnected. Retrying...")
initialize_smtp_connection()
def process_emails_and_auto_reply():
"""Checks for unread emails and sends an auto-reply if certain phrases are found."""
try:
# Add IMAP logic to retrieve and filter unread emails here
initialize_smtp_connection() # Ensure SMTP connection is active
# Example auto-reply (modify recipient and message as needed)
auto_reply_message = 'Subject: Automated Response\n\nThis is an automated reply.'
smtp_session.sendmail(EMAIL_ADDRESS, '[email protected]', auto_reply_message)
except smtplib.SMTPServerDisconnected:
print("Lost connection to SMTP server. Reinitializing...")
initialize_smtp_connection()
def main():
"""Main loop for continuously checking emails and handling auto-replies."""
while True:
try:
process_emails_and_auto_reply()
except Exception as error:
print(f"An error occurred: {error}")
if __name__ == "__main__":
main()
此结构现在应该可以正确处理断开连接并在必要时重新连接到 SMTP 服务器。