我目前正在编写一个应用程序,需要将电子邮件加载到内存中,添加附件并将相同的电子邮件发送回用户。这在过去运作良好,但我目前面临的问题是Content-Transfer-Encoding
base64
发送了一封电子邮件。
我发现了一个在线脚本,它将内置的Python电子邮件消息对象转换为multipart,但是每当我这样做时,原始电子邮件都不会以base64形式发送,现在每当我重新发送电子邮件时都会以纯文本形式显示。
有谁知道我怎么解决它?已经添加了(主要是已编辑的)电子邮件以及我用于将电子邮件转换为多部分的代码。感谢您的帮助。
# Before conversion
From: ██████████ <█████@██████.com>
To: ████████ <███████@██████.com>
Subject: █████████
Date: Fri, ██ ███ 2017 00:18:17 +0200
Content-Language: nl-NL
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: base64
MIME-Version: 1.0
cmVkYWN0ZWRyZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRy
ZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZHJl
ZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZA0K
# After conversion
Content-Type: multipart/mixed; boundary="===============0883378942=="
MIME-Version: 1.0
From: ██████████ <█████@██████.com>
To: ████████ <███████@██████.com>
Subject: █████████
Date: Fri, ██ ███ 2017 00:18:17 +0200
Content-Language: nl-NL
Content-Transfer-Encoding: base64
MIME-Version: 1.0
--===============0883378942==
Content-Type: text/html; charset="utf-8"
cmVkYWN0ZWRyZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRy
ZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZHJl
ZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZHJlZGFjdGVkcmVkYWN0ZWRyZWRhY3RlZA0K
--===============0883378942==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="foo.txt"
Hello world
--===============0883378942==--
# If this method is not used on an email object
# A `TypeError` is raised with the message "Attach is not valid on a message with a non-multipart payload"
def mail_to_multipart(mail):
"""
Convert an email to a multipart email
:param mail: Email object
:return: None
"""
if mail.is_multipart():
return mail
mail_new = MIMEMultipart("mixed")
headers = list((k, v) for (k, v) in mail.items() if k != "Content-Type")
for k, v in headers:
mail_new[k] = v
for k, v in headers:
del mail[k]
mail_new.attach(mail)
return mail_new
答案 0 :(得分:2)
显然,该问题与旧的多部分块中未保留的Content-Transfer-Encoding
标题有关,方法是更改以下行:
headers = list((k, v) for (k, v) in mail.items() if k != "Content-Type")
对此:
headers = list((k, v) for (k, v) in mail.items() if k not in ("Content-Type", "Content-Transfer-Encoding"))
修正了问题