Novice User
Novice User

Reputation: 3824

Downloading Attachment and Marking Mail as Unseen

I want to download the attachments from Unread Messages, but also does not want the messages to be flagged Seen.

The below code works, but currently setting the mail as Seen

Tried '(BODY.PEEK[HEADER])' , but then even mail download stopped.

import upload,checkFileAtServer,sha1sum,email, getpass, imaplib, os
detach_dir = '.'
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login('[email protected]','password')
m.select("inbox")

resp, items = m.search(None, "(UNSEEN)")
items = items[0].split()

for emailid in items:
  #resp, data = m.fetch(emailid, '(BODY.PEEK[HEADER])')
  resp, data = m.fetch(emailid, "(RFC822)")
  email_body = data[0][1]
  mail = email.message_from_string(email_body)
  temp = m.store(emailid,'+FLAGS', '\\Seen')
  m.expunge()

  if mail.get_content_maintype() != 'multipart':
    continue

  print "["+mail["From"]+"] :" + mail["Subject"]

  for part in mail.walk():
    if part.get_content_maintype() == 'multipart':
        continue
    if part.get('Content-Disposition') is None:
        continue

    filename = part.get_filename()
    att_path = os.path.join(detach_dir, filename)

    if not os.path.isfile(att_path) :
        fp = open(att_path, 'wb')
        fp.write(part.get_payload(decode=True))
        fp.close()
        sha1sum = sha1sum.calculateSHA1(att_path)
        print type(sha1sum)
        responseFromServer = checkFileAtServer.responseFromServer(sha1sum)
        if(responseFromServer == "NOT_CHECKED"):
            upload.uploadToSecureServer('root','root',att_path,att_path)

Anybody can guide me what am I missing ?

Thanks.

Upvotes: 0

Views: 524

Answers (1)

Jan Kundrát
Jan Kundrát

Reputation: 3816

If you do not want to mark a message as \Seen, don't call the STORE IMAP command and don't use FETCHable items which are documented to cause an implicit marking as such (yes, the RFC822 is an alias for BODY[] which causes the message to be marked as read).

Upvotes: 1

Related Questions