#!/usr/bin/python3 ''' Usage: for SMTP server test: mailtest.py SERVER_NAME submission LOGIN PASSWORD [/tmp/mailfile] mailtest.py SERVER_NAME smtps LOGIN PASSWORD [/tmp/mailfile] for IMAP server test: mailtest.py SERVER_NAME imaps LOGIN PASSWORD /tmp/mailfile example: MAIL FROM: RCPT TO: DATA From: Jan To: SAL Subject: Testing mail Date: Thu, 1 Apr 2020 14:17:54 -0000 Message-ID: <123xxxxxx@salstar.sk> Testing. ''' TLS_CMD = '''openssl s_client -connect %s:%s -starttls %s''' SSL_CMD = '''openssl s_client -connect %s:%s''' import sys, socket, time from subprocess import Popen, PIPE, DEVNULL, TimeoutExpired from threading import Thread from queue import Queue, Empty from base64 import b64encode if len(sys.argv)<4: print(__doc__) sys.exit() host, port, login, password = sys.argv[1:5] if len(sys.argv)>5: maildata = open(sys.argv[5], "rt").read() else: maildata = None if port=="submission": proto = "smtp" cmd = TLS_CMD % (host, port, proto) elif port=="smtps" or port=="smtp": proto = "smtp" cmd = SSL_CMD % (host, "smtps") elif port=="imaps" or port=="9993": proto = "imap" cmd = SSL_CMD % (host, port) elif port=="pop3s": proto = "pop3" cmd = SSL_CMD % (host, port) elif port=="pop3": proto = "pop3" cmd = "nc %s 110" % host else: print("ERROR: unknown protocol") sys.exit(1) print("Connecting...") print(cmd) conn = Popen(cmd.split(), bufsize=0, stdin=PIPE, stdout=PIPE, stderr=DEVNULL) def enqueue_output(out, queue): for line in iter(out.readline, b''): queue.put(line) out.close() queue = Queue() thread = Thread(target=enqueue_output, args=(conn.stdout, queue)) thread.daemon = True # thread dies with the program thread.start() def readall(rows=1): while True: try: out = queue.get_nowait() if out: print("< ", out.decode("utf-8").rstrip()) rows -= 1 except Empty: if rows<=0: break time.sleep(0.1) def write(data): readall() print("> ", data) #conn.communicate(data.encode("utf-8")) try: conn.stdin.write(data.encode("utf-8")+b"\n") except BrokenPipeError as err: print("Broken pipe") if proto=="smtp": write("HELO %s" % socket.gethostname()) write("AUTH LOGIN") write(b64encode(login.encode("utf-8")).decode("utf-8")) write(b64encode(password.encode("utf-8")).decode("utf-8")) if maildata: write(maildata.rstrip("\r\n")+"\n.") write("QUIT") elif proto=="imap": write("0 capability") write("0 LOGIN %s %s" % (login, password)) write('0 LIST "" "*"') write('0 EXAMINE INBOX') write('0 GETQUOTAROOT INBOX') write("0 logout") elif proto=="pop3": write("USER %s" % login) write("PASS %s" % password) write("LIST") write("QUIT") #readall()