Python imaplib download Gmail Text without downloading the full attachment
Asked Answered
T

1

1

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

By default,

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

will return the whole part of email, including the whole attachment encoded as text in the return data, which is sometimes huge and unnecessary.

I've searched over the internet and stackOverflow to find answer. Many of them mentioned to use

myGmail.fetch(mailUid, 'BODYSTRUCTURE')

to determined the email structure first, and then identify the part you want download. And I have also read the RFC 3501 doc about imap4 protocol, in which it mentioned that I can use

BODY[]<> to download the specific body part in Fetch command.

But I've tried many command in python imaplib like following:

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

but all of them failed with error message:

error: FETCH command error: BAD ['Could not parse command']

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

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

(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") "<[email protected]>" "image001.jpg" "BASE64" 4070
    ) 
    "RELATED"
  )
  ("APPLICATION" "PDF" ("NAME" "SAC 2012.pdf") NIL "SAC 2012.pdf" "BASE64" 20638)
  "MIXED"
 )
 )

Thanks!!!

Thirtytwomo answered 24/3, 2013 at 10:37 Comment(4)
Please don't leave out code - that makes it hard to track down and reproduce the problem. It's fine to blank username and password, but apart from that, everything should be ready to be pasted.Freightage
@Thirtytwomo - did you ever figure this out? If so, please share your code :)Councilor
@ZacharyBurt Actually eventually I didn't try getting the BODY structure and then parse. Instead, I just simply download all the content (including attachment) once. Which is a quick and dirty solution.Thirtytwomo
@Thirtytwomo thanks for responding. I filed a similar question here. #15732420 Feel free to follow along, I'll be adding bounty in 22 hours...Councilor
P
2

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

Philibeg answered 24/3, 2013 at 10:55 Comment(1)
Body part counting starts at 1.Trichosis

© 2022 - 2024 — McMap. All rights reserved.