Learning Python Network Programming

(Sean Pound) #1
Chapter 4
tmp, data = mailbox.search(None, 'ALL')
for num in data[0].split():
tmp, data = mailbox.fetch(num, '(RFC822)')
print('Message: {0}\n'.format(num))
pprint.pprint(data[0][1])
break
mailbox.close()
mailbox.logout()

if __name__ == '__main__':
username = input("Enter your email username: ")
password = getpass.getpass(prompt="Enter you account password:
")
check_email(username, password)

In this example, an instance of IMPA4_SSL(), that is, the mailbox object, has been
created. In this, we have taken the server address and port as arguments. Upon
successfully logging in with the login() method, you can use the select() method
for choosing the mail box folder that you want to access. In this example, the Inbox
folder has been selected. In order to read the messages, we need to request for the
data from the Inbox. One way to do that is to use the search() method. Upon the
successful reception of some mail metadata, we can use the fetch() method for
retrieving the e-mail message envelope part and data. In this example, the RFC 822
type of standard text message has been sought with the help of the fetch() method.
We can use the Python pretty print or the print module for showing the output on the
screen. Finally, apply the close() and the logout() methods to the mailbox object.


The preceding code will display an output similar to the following:


$ python3 fetch_email_imap.py
Enter your email username: [email protected]
Enter you Google password:
Message b'1'
b'X-Gmail-Received:
3ec65fa310559efe27307d4e37fdc95406deeb5a\r\nDelivered-To:
[email protected]\r\nReceived: by 10.54.40.10 with SMTP id
n10cs1955wrn;\r\n
[Message omitted]
Free download pdf