【问题标题】:Format subject email [duplicate]格式化主题电子邮件[重复]
【发布时间】:2020-04-23 17:45:48
【问题描述】:

我想恢复电子邮件的“SUBJECT”值

import imaplib
import os
import email

email_user = 'xxxxxxx@xxxxxxx'
email_pass = 'xxxxxxxx'

M = imaplib.IMAP4_SSL('imap.gmail.com', 993)
M.login(email_user, email_pass)
M.select('INBOX')

typ, message_numbers = M.search(None, 'ALL')

num = b'2420'
typ, data = M.fetch(num, '(RFC822)')

raw_email = data[0][1].decode('utf-8')
email_message = email.message_from_string(raw_email)

print(email_message['Subject'])

值是

=?UTF-8?Q?=5BNAS=5FLEBARS=5D_Active_Backup_for_Business_=2D_La_t=C3=A2che_?=
=?UTF-8?Q?de_sauvegarde_DBS_=2D_SIDEXIS_sur_NAS=5FLEBARS_est_termin=C3=A9e?=

但我想要这个编码

[NAS_LEBARS] Active Backup for Business - La tâche de sauvegarde DBS - SIDEXIS sur NAS_LEBARS est terminée

谢谢

【问题讨论】:

  • 你真的不能盲目地尝试decodedata;如果消息使用与您尝试的不同的编码,它将失败,即使它不正确,它也不会正确。请改用email_from_bytes()。

标签: python python-3.x email imaplib


【解决方案1】:

这几乎可以满足您的需要,它:

  • 获取每个编码行
  • 提取需要解码的部分
  • 转换,
    • 用空格替换每个“_”
    • 将每个“=XX”替换为具有该十六进制代码的字节
    • 保持所有其他字符不变
  • 将整个结果解码为 UTF-8 字节数组
import re

subject = [
    '=?UTF-8?Q?=5BNAS=5FLEBARS=5D_Active_Backup_for_Business_=2D_La_t=C3=A2che_?=',
    '=?UTF-8?Q?de_sauvegarde_DBS_=2D_SIDEXIS_sur_NAS=5FLEBARS_est_termin=C3=A9e?='
]


def convert_content(content):
    iter_content = iter(content)
    try:
        while True:
            ch = next(iter_content)
            if ch == '_':
                yield b' '
            elif ch == '=':
                yield bytearray.fromhex(next(iter_content)+next(iter_content))
            else:
                yield ch.encode('utf-8')
    except StopIteration:
        pass


def process(data):
    for line in data:
        m = re.match(r'=\?(?:utf|UTF)-8\?(?:q|Q)\?(.*)\?=', line)
        yield b''.join(convert_content(m.group(1))).decode('utf-8')


print(''.join(process(subject)))

输出:

[NAS_LEBARS] Active Backup for Business - La tâche de sauvegarde DBS - SIDEXIS sur NAS_LEBARS est terminée

【讨论】:

  • 顺便说一句,它假设匹配正则表达式时没有任何问题,并且每个“=”确实后面跟着一个十六进制代码,如果你不能,你应该让代码更健壮一点相信这是真的。
  • 我会在这里留下答案,但我不知道 email.header.decode_header 功能,在大多数情况下应该可以正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 2023-04-04
  • 2015-11-03
  • 1970-01-01
  • 2018-09-12
  • 2014-05-21
相关资源
最近更新 更多