This commit is contained in:
huangzhenpc
2025-02-26 18:38:10 +08:00
parent 36087b1e05
commit 1b81f4eebd

View File

@@ -44,12 +44,12 @@ class CustomSMTPServer(smtpd.SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
try:
# 记录接收到的邮件基本信息
logger.info(f'Received mail from {mailfrom} to {rcpttos}')
logger.info(f"Received mail from {mailfrom} to {rcpttos}")
# 验证收件人域名
for rcpt in rcpttos:
if not rcpt.endswith('@nosqli.com'):
logger.warning(f'Rejected mail to {rcpt}: invalid domain')
logger.warning(f"Rejected mail to {rcpt}: invalid domain")
continue
# 解析邮件
@@ -63,7 +63,7 @@ class CustomSMTPServer(smtpd.SMTPServer):
# 构建邮件数据
timestamp = datetime.now().isoformat()
message_id = email.get('Message-ID', f'<{timestamp}@nosqli.com>')
message_id = email.get('Message-ID', f"<{timestamp}@nosqli.com>")
email_data = {
'message_id': message_id,
@@ -80,10 +80,10 @@ class CustomSMTPServer(smtpd.SMTPServer):
# 存储邮件
self._store_email(email_data)
logger.info(f'Successfully processed mail: {message_id}')
logger.info(f"Successfully processed mail: {message_id}")
except Exception as e:
logger.error(f'Error processing email: {str(e)}', exc_info=True)
logger.error(f"Error processing email: {str(e)}", exc_info=True)
raise
def _get_email_body(self, email):
@@ -97,7 +97,7 @@ class CustomSMTPServer(smtpd.SMTPServer):
return email.get_payload(decode=True).decode()
return ""
except Exception as e:
logger.error(f'Error extracting email body: {str(e)}')
logger.error(f"Error extracting email body: {str(e)}")
return ""
def _process_attachments(self, email):
@@ -121,42 +121,42 @@ class CustomSMTPServer(smtpd.SMTPServer):
'size': len(attachment_data)
})
except Exception as e:
logger.error(f'Error processing attachments: {str(e)}')
logger.error(f"Error processing attachments: {str(e)}")
return attachments
def _store_email(self, email_data):
"""存储邮件到 Redis"""
try:
# 使用 message_id 作为主键
email_key = f'email:{email_data["message_id"]}'
email_key = f"email:{email_data['message_id']}"
redis_client.hmset(email_key, email_data)
# 为每个收件人创建索引
recipients = json.loads(email_data['recipients'])
for recipient in recipients:
recipient_key = f'recipient:{recipient}'
recipient_key = f"recipient:{recipient}"
redis_client.lpush(recipient_key, email_key)
# 创建时间索引
time_key = f'time:{email_data["timestamp"]}'
time_key = f"time:{email_data['timestamp']}"
redis_client.set(time_key, email_key)
# 设置过期时间可选这里设置为30天
redis_client.expire(email_key, 30 * 24 * 60 * 60)
except Exception as e:
logger.error(f'Error storing email: {str(e)}')
logger.error(f"Error storing email: {str(e)}")
raise
def start_smtp_server(host='0.0.0.0', port=25):
"""启动 SMTP 服务器"""
try:
logger.info(f'Starting SMTP server on {host}:{port}')
logger.info(f"Starting SMTP server on {host}:{port}")
server = CustomSMTPServer((host, port), None)
asyncore.loop()
except Exception as e:
logger.error(f'Error starting SMTP server: {str(e)}')
logger.error(f"Error starting SMTP server: {str(e)}")
raise