Let us first compress the current directory and then create an email message. We can send the email message via an external SMTP host, or we can use a local email server to do this. Like other recipes, let us get the sender and recipient information from parsing the command-line inputs.
Listing 5.3 shows how to convert an email folder into a compressed ZIP file as follows:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 5 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. import os import argparse import smtplib import zipfile import tempfile from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart def email_dir_zipped(sender, recipient): zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') zip = zipfile.ZipFile(zf, 'w') print ("Zipping current dir: %s" %os.getcwd()) for file_name in os.listdir(os.getcwd()): zip.write(file_name) zip.close() zf.seek(0) # Create the message print ("Creating email message...") email_msg = MIMEMultipart() email_msg['Subject'] = 'File from path %s' %os.getcwd() email_msg['To'] = ', '.join(recipient) email_msg['From'] = sender email_msg.preamble = 'Testing email from Python. ' msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=os.getcwd()[-1] + '.zip') email_msg.attach(msg) email_msg = email_msg.as_string() # send the message print ("Sending email message...") try: smtp = smtplib.SMTP('localhost') smtp.set_debuglevel(1) smtp.sendmail(sender, recipient, email_msg) except Exception as e: print ("Error: %s" %str(e)) finally: smtp.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Email Example') parser.add_argument('--sender', action="store",
dest="sender", default='[email protected]') parser.add_argument('--recipient', action="store",
dest="recipient") given_args = parser.parse_args() email_dir_zipped(given_args.sender, given_args.recipient)
Running this recipe shows the following output. The extra output is shown because we enabled the email debug level:
$ python 5_3_email_current_dir_zipped.py --recipient=faruq@localhost Zipping current dir: /home/faruq/Dropbox/PacktPub/pynet-cookbook/pynetcookbook_code/chapter5 Creating email message... Sending email message... send: 'ehlo [127.0.0.1] ' reply: '250-debian6.debian2013.com ' reply: '250-PIPELINING ' reply: '250-SIZE 10240000 ' reply: '250-VRFY ' reply: '250-ETRN ' reply: '250-STARTTLS ' reply: '250-ENHANCEDSTATUSCODES ' reply: '250-8BITMIME ' reply: '250 DSN ' reply: retcode (250); Msg: debian6.debian2013.com PIPELINING SIZE 10240000 VRFY ETRN STARTTLS ENHANCEDSTATUSCODES 8BITMIME DSN send: 'mail FROM:<[email protected]> size=9141 ' reply: '250 2.1.0 Ok ' reply: retcode (250); Msg: 2.1.0 Ok send: 'rcpt TO:<faruq@localhost> ' reply: '250 2.1.5 Ok ' reply: retcode (250); Msg: 2.1.5 Ok send: 'data ' reply: '354 End data with <CR><LF>.<CR><LF> ' reply: retcode (354); Msg: End data with <CR><LF>.<CR><LF> data: (354, 'End data with <CR><LF>.<CR><LF>') send: 'Content-Type: multipart/mixed; boundary="===============0388489101==...[TRUNCATED] reply: '250 2.0.0 Ok: queued as 42D2F34A996 ' reply: retcode (250); Msg: 2.0.0 Ok: queued as 42D2F34A996 data: (250, '2.0.0 Ok: queued as 42D2F34A996')