Python imaplib download gmail text without downloading full attachments

I am using 'imaplib' in python to get email from a Gmail account. But I just want to know the content of the email, the name of the attachment, but I do not need to download the full application.

Default

myGmail = imaplib.IMAP4_SSL(...) .... (respCode, data) = myGmail.fetch(mailUid, 'RFC822') 

will return the entire part of the email, including the entire attachment encoded as text in the returned data, which is sometimes huge and not necessary.

I searched the web and stackOverflow to find the answer. Many of them mentioned that they use

 myGmail.fetch(mailUid, 'BODYSTRUCTURE') 

to first determine the structure of the email, and then determine the part that you want to download. And I also read RFC 3501 on the imap4 protocol, in which he mentioned that I can use

BODY [] <> to load a specific part of the body in the Fetch command.

But I have tried many commands in python imaplib as below:

 (rCode, data) = myGmail.fetch(mailUid, 'BODY[0]') (rCode, data) = myGmail.fetch(mailUid, 'BODY0') (rCode, data) = myGmail.fetch(mailUid, 'BODY[TEXT]') 

but all of them are not generated with an error message:

error: FETCH command error: BAD ['Could not execute command "]

So can anyone tell me how to use this command in python imaplib for gmail?

And just for your reference, BODYSTRUCTURE for the above email:

 (BODY ( ( ( ("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "QUOTED-PRINTABLE" 1742 33) ("TEXT" "HTML" ("CHARSET" "us-ascii") NIL NIL "QUOTED-PRINTABLE" 17976 485) "ALTERNATIVE" ) ( "IMAGE" "JPEG" ("NAME" "image001.jpg") "< image001.jpg@01CD029F.6831C440 >" "image001.jpg" "BASE64" 4070 ) "RELATED" ) ("APPLICATION" "PDF" ("NAME" "SAC 2012.pdf") NIL "SAC 2012.pdf" "BASE64" 20638) "MIXED" ) ) 

Thanks!!!

+1
source share
1 answer

Just replace BODY[0] with (BODY[1]) .

+2
source

Source: https://habr.com/ru/post/947145/


All Articles