#!/usr/bin/env python3 """ Copyright (C) 2017 Assaf Gordon License: Simplified BSD (2-clause) A simple examlpe script of preparing a multipart mime message (main text + attachments), and sending it using an SMTP server. """ import smtplib, os from getpass import getuser from socket import gethostname from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate from email import encoders import magic # requires 'python-magic' package send_from= getuser() + "@" + gethostname() send_to= ["assafgordon@gmail.com"] subject="testing 1 2 3" msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime = True) msg['Subject'] = subject # First part, attach as inline content f = "/etc/motd" text = open(f).read() msg.attach( MIMEText(text) ) # Other files, store as attachments files = [ "/usr/share/pixmaps/debian-logo.png", "/bin/sed" ] for f in files: # Detect mime type mime = magic.from_file(f,mime=True) (main,sub) = mime.split("/",2) # Read the file, create mime part as 'attachment' part = MIMEBase(main,sub) part.set_payload( open(f,"rb").read() ) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f))) msg.attach(part) ## Print the entire mime message. ## This can be pipe'd into "/usr/sbin/sendmail -t" to be send ## (assuming sendmail is insalled and properly configured) if True: print(msg) ## Send the message by SMTP. ## Can be sent to localhost if exim4/postfix/etc are installed and configured. ## Otherwise, add host/port to the connect() call (and user/password login, too) if False: mailer = smtplib.SMTP() mailer.connect() mailer.sendmail(send_from, send_to, msg.as_string()) mailer.quit()