How it works...

After importing the modules that will be used and defining the credentials, we connect to the server in step 3.

Step 4 connects to the inbox. This is a default folder in Gmail that contains the received email.

Of course, you may need to read a different folder. You can get a list of all folders by calling mail.list().

In step 5, first a list of UIDs is retrieved for all the emails in the inbox by calling .uid('search', None, "ALL"). The last email received is then retrieved again from the server through a fetch action with .uid('fetch', latest_email_uid, '(RFC822)'). This retrieves the email in RFC822 format, which is the standard. Note that retrieving the email marks it as read.

The .uid command allows us to call IMAP4 commands, returning a tuple with the result (OK or NO) and the data. If there's an error, it will raise the proper exception.

The BytesParser module is used to transform from the raw RFC822 email into a Python object. This is done in Step 6.

The metadata, including details such as the subject, the sender, and the timestamp, can be accessed like a dictionary, as shown in step 7. The addresses can be parsed from raw text format to separate the part with email.utils.parseaddr.

Finally, the content can be unfolded and extracted. If the type of the email is multipart, each of the parts can be extracted by iterating through .get_payload(). The one that's easier to deal with is plain/text, so assuming it is present, the code in step 8 will extract it.

The email body is stored in the payload variable.

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

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