Python Forum

Full Version: code works, but how? What does the last line do?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have to download 130 student photos from my email box. I am trying to get Python to do this. I can only dig up bits of code from the internet, patch them together and hope it works.

I will make a loop, but I first tried with just 1 email. This code works.

#! /usr/bin/python3
# should get image attachments from emails

import sys
import pyzmail
import email
from imapclient import IMAPClient


HOST = 'imap.qq.com'
USERNAME = '[email protected]'
PASSWORD = 'myIMAPpassword'


pathToFiles = '/home/pedro/getEmailtexts/emailTexts/'
server = IMAPClient(HOST, use_uid=True, ssl=True)
server.login(USERNAME, PASSWORD)
select_info = server.select_folder('Inbox')

rawMessage = server.fetch([59], ['BODY[]', 'FLAGS']) # I know that UID 59 has a photo, I sent it.

message = pyzmail.PyzMessage.factory(rawMessage[59][b'BODY[]'])
len(message.get_payload()) # response is 2
attachment = message.get_payload()[1]
attachment.get_content_type() # response is 'image/jpeg'
open(pathToFiles + 'rob.jpg', 'wb').write(attachment.get_payload(decode=True)) # saves the photo to my computer
Could someone please elaborate in the last line? I like to try to understand what is going on (I don't really understand).
Can this be broken into steps? What is 'wb'?
the line is commented and is doing exactly that - save the photo (i.e. the attachment) to hard drive at pathToFiles
it is same as
with open(pathToFiles + 'rob.jpg', 'wb') as f:
    f.write(attachment.get_payload(decode=True))