0

I adapted script from http://tech.franzone.blog/2012/11/24/listing-imap-mailboxes-with-python/ to identify each and every mailbox on my IMAP4 email sever. The following script is designed to backup email messages on the server.

The script below works fine EXCEPT if the mailbox targeted contains the ampersand character (Eg "Here & there"). Any time I run the script on a mailbox containing an ampersand, I get an "ERROR: Unable to open mailbox" message in the log. Note that the mailbox is already surrounded by quotes. Anyway, I tried & in place of & without success. Ideas?

import sys
import imaplib

IMAP_SERVER = '<email server name>'
EMAIL_ACCOUNT = str(sys.argv[1]) 
EMAIL_FOLDER = "Inbox.Here & there"
OUTPUT_DIRECTORY = '<local directory>' + EMAIL_ACCOUNT + '/' + EMAIL_FOLDER
PASSWORD = str(sys.argv[2])
localtime = time.asctime( time.localtime(time.time()) )

def process_mailbox(M):
    """
    Dump all emails in the folder to files in output directory.
    """

    logging.basicConfig(level=logging.DEBUG, 
filename="DailyFullEmailBackup.log", filemode="a+", format="%(asctime)-15s, %(levelname)-8s %(message)s")

    rv, data = M.search(None, "ALL")
    if rv != 'OK':
        logging.debug ("No messages found!")
        return

    for num in data[0].split():
        rv, data = M.fetch(num, '(BODY.PEEK[])')
        if rv != 'OK':
            logging.debug ("ERROR getting message %s", num)
            return
        logging.debug ("Writing message %s", num)
        f = open('%s/%s.eml' %(OUTPUT_DIRECTORY, num), 'wb')
        f.write(data[0][1])
        f.close()

def main():
    logging.basicConfig(level=logging.DEBUG, filename="debug.log", 
filemode="a+", format="%(asctime)-15s, %(levelname)-8s %(message)s")
    logging.debug ("Begin.")
    M = imaplib.IMAP4_SSL(IMAP_SERVER)
    M.login(EMAIL_ACCOUNT, PASSWORD)
    rv, data = M.select(EMAIL_FOLDER)
    if rv == 'OK':
        logging.debug ( "Processing mailbox: %s", EMAIL_ACCOUNT)
        logging.debug ( "Processing folder: %s", EMAIL_FOLDER)
        process_mailbox(M)
        M.close()
    else:
        logging.debug  ("ERROR: Unable to open mailbox %s", EMAIL_FOLDER)
    M.logout()

if __name__ == "__main__":
    main()

localtime = time.asctime( time.localtime(time.time()) )
print "Finish time: ", localtime
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

Yes, IMAP mailboxes use a modified UTF-7 encoding, which uses & as the encoding character. I don't believe imaplib has UTF-7 encoding built in, but you can use the LIST command to get the actual name of the folder. It is likely Inbox.Here &- There. Also note that spaces may require quotes to be put around the folder name "Inbox.Here &- There"

Max
  • 10,701
  • 2
  • 24
  • 48