Email Completed Checklists
Description
This script sends a record of a completed checklist to the provided email address(es).
This also includes any image attachments.
Full Script
import email, smtplib, ssl from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import os import sys import traceback from email import encoders from datetime import datetime #Set default details host='mail.host' username='mail.username' password='mail.password' recipient='recipient' sender='sender' port=server port asset = "Unknown Asset" checklist = "Unknown Checklist" user = "Unknown User" assetid = "1" tm = datetime.now().strftime("%Y/%m/%d %H:%M:%S") #Get submission details from environment variables try: asset = os.environ["assetname"] except: print "No Asset Provided" sys.exit(0) try: assetid = os.environ["assetid"] except: print "No Asset ID Provided" sys.exit(0) try: checklist = os.environ["checklist"] except: print "No Checklist Provided" sys.exit(0) try: user = os.environ["user"] except: print "No User Provided" sys.exit(0) #Prepare an SSL context ss = ssl.create_default_context() #Prepare message message = MIMEMultipart("alternative") message["Subject"] = asset + " " + checklist + " by " + user message["From"] = sender message["To"] = recipient #Message content goes here plain = """\ The {checklist} has been completed by {user} for {asset} on {date}. """ html = """\ <html> <body> <table width="100%"> <td><label>Checklist</label></td><td>{checklist}</td></tr> <td><label>Asset</label></td><td>{asset}</td></tr> <td><label>User</label></td><td>{user}</td></tr> <td><label>Date/Time</label></td><td>{date}</td></tr> </table> </body> </html> """ def Sub(st,ass,chk,usr,dt): return st.replace("{checklist}",chk).replace("{asset}",ass).replace("{user}",usr).replace("{date}",dt) #print Sub(plain,asset,checklist,user,tm) #Add both plain-text and HTML versions to the email pa = MIMEText(Sub(plain,asset,checklist,user,tm),"plain") pb = MIMEText(Sub(html,asset,checklist,user,tm),"html") message.attach(pa) message.attach(pb) #Include any attachments try: atcount = os.environ['attachments'] #print "Found " + str(atcount) + " attachments!" if atcount > 0: for x in range(0,int(atcount)): with open(os.environ['at' + str(x)],"rb") as attach: part = MIMEBase("application","octet-stream") part.set_payload(attach.read()) encoders.encode_base64(part) ext = os.environ['at' + str(x)].rpartition(".")[-1] part.add_header("Content-Disposition","attachment; filename=photo"+str(x)+"." + ext) message.attach(part) except: traceback.print_exc() pass #Send the email server = smtplib.SMTP_SSL(host,port) server.login(username,password) server.sendmail(sender,recipient,message.as_string()) #If everything worked out, send the word 'OK'. print 'OK'