Python 100 project #39: Email Inbound-SMTP Test

When introducing a new security layer to the email service, sometimes I need to test if those servers are working well without changing anything in production server. It is usually quite difficult as Email services are usually company wide. But if I can specify the smtp server to use(in this case the new security appliance server ip address), it’s possible at least I can see if that server is configured correctly(to receive email).


Output Example:

$ python3 
This utility sends the email using specified SMTP server.
Please enter smtp server:

Please enter from address:

Please enter to address:

Please enter the subject of this email: this is a test subject

Please enter mail body: this is a test body from python3

Please enter file name (in full path) if any separated by space: /Users/XXXXX/test.csv /Users/XXXXXX/

Email has been sent.



Here is the code:

import smtplib
from email import encoders, utils
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import mimetypes

def attachment(filename):
    mimetype, mimeencoding = mimetypes.guess_type(filename)
    if mimeencoding or (mimetype is None):
        mimetype = 'application/octet-stream'
    maintype, subtype = mimetype.split('/')
    if maintype == 'text':
        with open(filename, 'r') as fd:
            retval = MIMEText(, _subtype=subtype)
        with open(filename, 'rb') as fd:
            retval = MIMEBase(maintype, subtype)
    retval.add_header('Content-Disposition', 'attachment', filename=filename)
    return retval

def create_message(fromaddr, toaddr, subject, message, files):
    msg = MIMEMultipart()
    msg['To'] = toaddr
    msg['From'] = fromaddr
    msg['Subject'] = subject
    msg['Date'] = utils.formatdate(localtime=True)
    msg['Message-ID'] = utils.make_msgid()

    body = MIMEText(message, _subtype='plain')

    for filename in files:
    return msg.as_string()

def send(smtpsrv, fromaddr, toaddr, message):
    s = smtplib.SMTP(host=smtpsrv, port=25)
    s.sendmail(fromaddr, [toaddr], message)

if __name__ == '__main__':

    print("This utility sends the email using specified SMTP server.")
    smtpsrv = input("Please enter smtp server: ")
    fromaddr = input("Please enter from address: ")
    toaddr = input("Please enter to address: ")
    subject = input("Please enter the subject of this email: ")
    msg = input("Please enter mail body: ")
    attach = input("Please enter file name (in full path) if any separated by space: ").split()
    message = create_message(fromaddr, toaddr, subject, msg, attach)
        send(smtpsrv, fromaddr, toaddr, message)
        print("Email has been sent.")
        print("Something wrong...")