import smtplib
import smtpd
import asyncore
import email.utils
from email.mime.text import MIMEText
import threading


class SMTPReceiver(smtpd.SMTPServer):

    def process_message(self, peer, mailfrom, rcpttos, data):
        print 'Receiving message from:', peer
        print 'Message addressed from:', mailfrom
        print 'Message addressed to  :', rcpttos
        print 'Message length        :', len(data)
        print data

        def send_response():
            msg = MIMEText('Hello world!')
            msg['To'] = email.utils.formataddr(('Recipient', mailfrom))
            msg['From'] = email.utils.formataddr(
                ('Author', 'jsternberg@example.org'))
            msg['Subject'] = ''

            print 'Connecting to mail server'
            server = smtplib.SMTP()
            server.set_debuglevel(1)
            server.connect()
            print 'Attempting to send message'
            try:
                server.sendmail(
                    'jsternberg@example.org',
                    [mailfrom],
                    msg.as_string())
            except Exception as ex:
                print 'Could not send mail', ex
            finally:
                server.quit()
            print 'Finished sending message'
        threading.Thread(target=send_response).start()
        return


def main():
    server = SMTPReceiver(('', 2025), None)
    asyncore.loop()

if __name__ == '__main__':
    main()
