0

I have this code, and it seems to be able to log into the Gmail and view the emails (Unread email become marked as read). However, there is no downloading occurring, and I'm not sure why. Any ideas on how to make this happen?

import email
import getpass, imaplib
import os
import sys

detach_dir = '.'
if 'attachments' not in os.listdir(detach_dir):
    os.mkdir('attachments')

userName = input('Enter your GMail username:')
passwd = getpass.getpass('Enter your password: ')

imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
typ, accountDetails = imapSession.login(userName, passwd)
if typ != 'OK':
    print ('Not able to sign in!')
    raise

imapSession.select('Inbox')
typ, data = imapSession.search(None, 'ALL')
if typ != 'OK':
        print ('Error searching Inbox.')
        raise

     # Iterating over all emails
for msgId in data[0].split(): typ, messageParts = imapSession.fetch(msgId, 
'(RFC822)')
if typ != 'OK':
    print ('Error fetching mail.')
    raise

    emailBody = messageParts[0][1]
    mail = email.message_from_string(emailBody)
for part in mail.walk():
    if part.get_content_maintype() == 'multipart':
        # print part.as_string()
        continue
    if part.get('Content-Disposition') is None:
            # print part.as_string()
        continue
    fileName = part.get_filename()

    if bool(fileName):
        filePath = os.path.join(detach_dir, 'attachments', fileName)
        if not os.path.isfile(filePath) :
            print (fileName)
            fp = open(filePath, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()
imapSession.close()
imapSession.logout()
MontyB
  • 1
  • fileName = part.get_filename() -> filePath = os.path.join(detach_dir, 'attachments', fileName) is an attack waiting to happen. – Max Jul 17 '18 at 19:12
  • Use [Users.messages.attachments: get](https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get) to get the specified message attachment. For the full code implementation in Python, check this [SO Post](https://stackoverflow.com/a/27335699). – ReyAnthonyRenacia Jul 18 '18 at 11:17

1 Answers1

0

I was working with similar code and I had the same problem. In order to solve it, I changed

mail = email.message_from_string(emailBody)

to

mail = email.message_from_bytes(emailBody)

which worked for me. Hope it helps!

christheliz
  • 176
  • 2
  • 15