0

I cannot figure out why the following script will not overwrite a file with the same name. I've used chmod 777 and the directory is writeable. The script executes perfectly when a new file is retrieved, however it doesn't not replace existing files and desired.

this script crawls through Gmail, looks for a subject line and retrieves attachments to the correct directory.

#!/usr/bin python3
# read emails and detach attachment in attachments directory
 
import email
import getpass, imaplib
import os
import sys
import time

detach_dir =  '/var/www/html/attachments'
if not os.path.exists(detach_dir):
    os.makedirs(detach_dir)

userName = 'username'
passwd = 'password'
 
try:
    imapSession = imaplib.IMAP4_SSL('imap.gmail.com',993)
    typ, accountDetails = imapSession.login(userName, passwd)
    if typ != 'OK':
        print ('Not able to sign in!')
        raise Exception
 
    imapSession.select('Inbox')
    typ, data = imapSession.search(None, 'SUBJECT', '"IMAGES"')
    if typ != 'OK':
        print ('Error searching Inbox.')
        raise Exception

    for msgId in data[0].split():
        typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
 
        if typ != 'OK':
            print ('Error fetching mail.')
            raise Exception
 
        emailBody = messageParts[0][1] 
        mail = email.message_from_bytes(emailBody) 
 
        for part in mail.walk():
 
            if part.get_content_maintype() == 'multipart':
 
                continue
            if part.get('Content-Disposition') is None:
 
                continue
 
            fileName = part.get_filename()
 
            if bool(fileName): 
                filePath = os.path.join(detach_dir, fileName)
                if not os.path.isfile(filePath) : 
                    print (fileName)
                    print (filePath)
                    fp = open(filePath, 'wb')
                    fp.write(part.get_payload(decode=True))
                    fp.close()
 
    #MOVING EMAILS TO PROCESSED PART BEGINS HERE
    imapSession.select(mailbox='inbox', readonly=False)
    resp, items = imapSession.search(None, 'All')
    email_ids = items[0].split()
    for email in email_ids:
        latest_email_id = email
 
        #move to processed
        result = imapSession.store(latest_email_id, '+X-GM-LABELS', 'Processed')
 
        if result[0] == 'OK':
            #delete from inbox
            imapSession.store(latest_email_id, '+FLAGS', '\\Deleted')
 
    #END OF MOVING EMAILS TO PROCESSED
 
    imapSession.close()
    imapSession.logout()
 
except :
    print ('No attachments were downloaded')

Any thoughts on what I need to change to have the file be overwritten if a file of the same name already exists?

3
  • 1
    If you want your code to write the file whether or not the file already exists, then get rid of the os.path.isfile(filePath) check - just do the following code unconditionally. Commented Jun 23, 2023 at 16:53
  • You can remove it, before write again or give the file name a timestamp. But ‘w’ mode should overwrite an exiting file. Commented Jun 23, 2023 at 16:59
  • @jasonharper that did the trick! Removing 'if bool(fileName): if not os.path.isfile(filePath) :' allowed the existing file to be overwritten. Thanks for catching it! Commented Jun 23, 2023 at 17:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.