import socket
import smtplib
from email.message import EmailMessage

# Configuration
HOST = "0.0.0.0"  # Listen on all interfaces
PORT = 8502        # Telnet port
USERNAME = "USERNAME"  # Example username - ensure BBS.INIT line35705 matches
PASSWORD = "PASSWORD"  # Example password - ensure BBS.INIT line35706 matches
SMTP_SERVER = "yoursmtpserveraddress.com" #your smtp server address
SMTP_PORT = 587
EMAIL_FROM = "sysop@sysop.bbs" #Add your valid email address here
EMAIL_TO = "sysop@sysop.bbs" #Your desired recipient even if same...
EMAIL_SUBJECT = "BBS Event Notification"
EMAIL_PASSWORD = "MyEmailServerPassword"  # your SMTP server password credential
TIMEOUT_SECONDS = 10  # Timeout for user input

def send_email(event_message):
    """Send an email notification with multi-line event message."""
    try:
        print("Connecting to SMTP server...")  # Debug log

        # Create an email message with headers
        msg = EmailMessage()
        msg["Subject"] = EMAIL_SUBJECT
        msg["From"] = EMAIL_FROM
        msg["To"] = EMAIL_TO
        msg["Reply-To"] = EMAIL_FROM  # Set custom Reply-To
        msg.set_content(event_message)  # Allow multi-line content

        # Connect to SMTP
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT, timeout=10)
        server.starttls()
        server.login(EMAIL_FROM, EMAIL_PASSWORD)
        server.send_message(msg)  # Send the email using the email.message object
        server.quit()

        print("Email successfully sent!")  # Debug log
        return True
    except Exception as e:
        print(f"Email error: {e}")
        return str(e)  # Return error message

def receive_multiline(client_socket):
    """Receive multiple lines of input until 'END' is entered or timeout occurs."""
    client_socket.send(b"Enter Event (type 'END' on a new line to finish):\r\n")
    lines = []
    client_socket.settimeout(TIMEOUT_SECONDS)  # Set timeout

    try:
        while True:
            line = receive_line(client_socket)
            if line is None:
                break  # Timeout or client disconnected
            if line.strip().upper() == "END":
                return "\n".join(lines)  # Preserve newlines in email body
            lines.append(line)
    except socket.timeout:
        client_socket.send(b"\r\nTimeout reached. Connection closing.\r\n")
        print("Timeout reached. Closing connection.")
        return None  # Indicate timeout occurred

    return "\n".join(lines)

def receive_line(client_socket):
    """Receive a full line from the client, handling Telnet input properly."""
    data = b""
    while True:
        try:
            chunk = client_socket.recv(1)
            if not chunk:
                return None  # Client disconnected
            if chunk in [b"\n", b"\r"]:  # End of input line
                break
            data += chunk
        except socket.timeout:
            return None  # Timeout reached
    return data.decode(errors='ignore').strip()

def handle_client(client_socket):
    """Handle the Telnet connection."""
    try:
        client_socket.send(b"Username: ")
        username = receive_line(client_socket)
        print(f"Received username: {username}")  # Debug log

        client_socket.send(b"Password: ")
        password = receive_line(client_socket)
        print(f"Received password: {password}")  # Debug log

        if username == USERNAME and password == PASSWORD:
            event_message = receive_multiline(client_socket)  # Allow multi-line input
            if event_message:
                print(f"Received event:\n{event_message}")  # Debug log
                result = send_email(event_message)
                if result is True:
                    client_socket.send(b"Event notification sent.\r\n")
                else:
                    error_msg = f"Failed to send notification: {result}\r\n"
                    client_socket.send(error_msg.encode())  # Send SMTP error message
            else:
                client_socket.send(b"No event entered. Closing connection.\r\n")
        else:
            client_socket.send(b"Authentication failed.\r\n")

    except Exception as e:
        print(f"Error handling client: {e}")

    finally:
        print("Closing connection")  # Debug log
        client_socket.close()

def start_server():
    """Start the Telnet server."""
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((HOST, PORT))
    server.listen(5)
    print(f"Server listening on port {PORT}...")

    while True:
        try:
            client_socket, addr = server.accept()
            print(f"Connection from {addr}")
            handle_client(client_socket)
        except KeyboardInterrupt:
            print("\nServer shutting down.")
            server.close()
            break

if __name__ == "__main__":
    start_server()

#Instructions:
#Modify the USERNAME, PASSWORD, SMTP_SERVER, and email details.
#Start the script: python3 itchynotify.py
#Connect via Telnet: telnet <your_server_ip> 8502 (see BBS.INIT line 35705)
#Enter the username, password, and event (BBS.INIT lines 35705-35707)
#The script will send the event via email.
