add support for custom chatids

This commit is contained in:
Shihaam Abdul Rahman 2024-09-21 02:11:54 +05:00
parent 5c99e21cfe
commit e59560fafd
Signed by: shihaam
GPG Key ID: 6DA2E87EBC227636

View File

@ -4,14 +4,15 @@ from aiosmtpd.controller import Controller
from email.parser import BytesParser
from email.policy import default
import telegram
import re
# Telegram configuration
TELEGRAM_API_KEY = os.getenv('TELEGRAM_API_KEY')
TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')
DEFAULT_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID') # Fallback chat ID
# SMTP configuration
SMTP_HOST = '0.0.0.0' # Listen on all interfaces
SMTP_PORT = 2525 # Standard SMTP port
SMTP_PORT = 2525 # Alternative SMTP port
class SMTPHandler:
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
@ -27,11 +28,26 @@ class SMTPHandler:
telegram_message = f"Subject: {subject}\n\n{body}"
# Extract chat ID from the recipient email address
chat_id = self.extract_chat_id(envelope.rcpt_tos[0])
bot = telegram.Bot(TELEGRAM_API_KEY)
await bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=telegram_message)
try:
await bot.send_message(chat_id=chat_id, text=telegram_message)
print(f"Message sent to Telegram chat ID: {chat_id}")
except telegram.error.BadRequest:
print(f"Failed to send message to chat ID: {chat_id}. Using default chat ID.")
await bot.send_message(chat_id=DEFAULT_CHAT_ID, text=telegram_message)
return '250 Message accepted for delivery'
def extract_chat_id(self, email):
match = re.match(r'(\d+)@telegram-relay\.local', email)
if match:
return match.group(1)
print(f"Invalid email format: {email}. Using default chat ID.")
return DEFAULT_CHAT_ID
async def start_smtp_server():
controller = Controller(SMTPHandler(), hostname=SMTP_HOST, port=SMTP_PORT)
controller.start()