【问题标题】:imaplib mailbox with "&" won't open带有“&”的 imaplib 邮箱无法打开
【发布时间】:2019-02-28 04:36:23
【问题描述】:

我改编了 http://tech.franzone.blog/2012/11/24/listing-imap-mailboxes-with-python/ 的脚本来识别我的 IMAP4 电子邮件服务器上的每个邮箱。以下脚本旨在备份服务器上的电子邮件。

下面的脚本可以正常工作,除非目标邮箱包含 & 字符(例如“Here & there”)。每当我在包含 & 符号的邮箱上运行脚本时,我都会在日志中收到“错误:无法打开邮箱”消息。请注意,邮箱已经用引号括起来。无论如何,我尝试用& 代替&,但没有成功。想法?

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

【问题讨论】:

    标签: python imaplib


    【解决方案1】:

    是的,IMAP 邮箱使用修改后的 UTF-7 编码,它使用 & 作为编码字符。我不相信 imaplib 内置了 UTF-7 编码,但您可以使用 LIST 命令来获取文件夹的实际名称。很可能是Inbox.Here &amp;- There。另请注意,空格可能需要在文件夹名称周围加上引号"Inbox.Here &amp;- There"

    【讨论】:

    • 我使用 franzone 的脚本得到的列表只是说“Inbox.Here & There”。 UTF-7 对我来说是新的。谢谢。
    猜你喜欢
    • 2014-12-29
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    相关资源
    最近更新 更多