How it works...

We have used Python's zipfile, smtplib, and an email module to achieve our objective of emailing a folder as a zipped archive. This is done using the email_dir_zipped() method. This method takes two arguments: the sender and recipient's email addresses to create the email message.

In order to create a ZIP archive, we create a temporary file with the tempfile module's TemporaryFile() class. We supply a filename, prefix, mail, and suffix, .zip. Then, we initialize the ZIP archive object with the ZipFile() class by passing the temporary file as its argument. Later, we add files of the current directory with the ZIP object's write() method call.

To send an email, we create a multipart MIME message with the MIMEmultipart() class from the email.mime.multipart module. Like our usual email message, the subject, recipient, and sender information is added in the email header.

We create the email attachment with the MIMEBase() method. Here, we first specify the application/ZIP header and call set_payload() on this message object. Then, in order to encode the message correctly, the encode_base64() method from encoder's module is used. It is also helpful to use the add_header() method to construct the attachment header. Now, our attachment is ready to be included in the main email message with an attach() method call.

Sending an email requires you to call the SMTP() class instance of smtplib. There is a sendmail() method that will utilize the routine provided by the OS to actually send the email message correctly. Its details are hidden under the hood. However, you can see a detailed interaction by enabling the debug option as shown in this recipe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.214.60