admin管理员组

文章数量:1559724

背景

这两天收到系统通知邮件,提示我的企业邮箱空间容量不够,再过两天就无法接收邮件。因此,我看了一下邮箱,想着将这些邮件归档存到本地。

我尝试过用Foxmail导出邮件,但是速度太慢了。

突发奇想,让ChatGPT帮我写一个脚本,用Python3来实现IMAP导出全部邮件。

经过几次代码优化迭代,形成了下面可以导出的脚本。

代码实现

import hashlib
import imaplib
import os
import email
from email.header import decode_header
from datetime import datetime
from imapclient import imap_utf7


def get_decoded_header(header: str) -> str:
    try:
        decoded_header = email.header.decode_header(header)
        header_value, encoding = decoded_header[0]

        if isinstance(header_value, bytes):
            try:
                if encoding and encoding.lower() != "unknown-8bit":
                    return header_value.decode(encoding)
                else:
                    raise LookupError("unknown-8bit encoding")
            except (UnicodeDecodeError, LookupError):
                # 尝试使用备选编码进行解码
                alt_encodings = ["gb18030", "gbk", "gb2312", "big5", "utf-8"]
                for alt_encoding in alt_encodings:
                    try:
                        return header_value.decode(alt_encoding)
                    except UnicodeDecodeError:
                        continue
                return header_value.decode("utf-8", errors="replace")

        return header_value
    except Exception as e:
        print(f"Error while decoding header: {
     e<

本文标签: 腾讯企业邮箱脚本并保存邮件