#!/usr/bin/pythonfromemail.mime.multipartimportMIMEMultipartfromemail.mime.textimportMIMETextfromemail.mime.baseimportMIMEBasefromemailimportencodersimportsysimportStringIOimportatexit# Back up stdout and stderr. We'll overwrite them by StringIO to save the# output to a string.stdout_copy=sys.stdout
stderr_copy=sys.stderr
f=StringIO.StringIO()sys.stdout=f
sys.stderr=f# The MIME message we're going to wrap the program's output in.msg=MIMEMultipart()# This is the boundary I set in my crontab file. Kludgy, but I knew no other# way to send multipart files from cron. To reproduce it, add the following# to your crontab:## CONTENT_TYPE='multipart/mixed; boundary="------------040907050602020300000601"'msg.set_boundary('------------040907050602020300000601')# At exit, print f's contents as a MIME message.defflush_f():# Rewind the f StringIO so that f.read() will read all the data.f.seek(0)# Restore stdout and stderr - this will let us print to the program's# standard output. Note that we overwrite stderr with the stdout - this# will let us see the error messages in crontab e-mails.sys.stdout=stdout_copy
sys.stderr=stdout_copy# Add the stdout contents to the message body.stdout_contents=MIMEText(f.read(),"plain")msg.attach(stdout_contents)# Attach the attachments. We use "unknown" to trick Thunderbird into# thinking that the file is binary.forfilenameinfilenames:iffilename.endswith(".png"):attachment=MIMEBase("image","png")else:attachment=MIMEBase("application","unknown")attachment.set_payload(open(filename).read())attachment.add_header('Content-Disposition','attachment',filename=filename)encoders.encode_base64(attachment)msg.attach(attachment)# Print the final message.print(msg.as_string())atexit.register(flush_f)print("Hello, world!")filenames=["/etc/redhat-release"]