就像您链接到的示例一样,您必须有多个 MIME 部分,每个部分都有一个单独的 Content-Language: 标头。
这是重新创建示例的尝试。不幸的是,如果您使用suben['Content-Language'] = 'en-GB' 添加它并使用add_header 将其移动到附件的标题中,Python 似乎会清除Content-Language: 标题,所以我不确定这是否会起作用。在我添加的Content-Disposition: 和 Python 添加的之间也存在令人讨厌的冲突。如果我使用msg.add_attachment()suben, 'rfc822', 'inline'),我会收到一条愤怒的错误消息,指出message/rfc822 部件不支持'inline'。 (也许您需要为这种类型创建一个新的内容管理器?)
from email.message import EmailMessage
msg = EmailMessage()
msg['From'] = 'Nik@example.com'
msg['To'] = 'Nathaniel@example.com'
msg['Subject'] = 'Example of a message in Spanish and English'
msg['Content-Disposition'] = 'inline' # redundant?
msg.set_content = """\
This is a message in multiple languages. It says the
same thing in each language. If you can read it in one language,
you can ignore the other translations. The other translations may be
presented as attachments or grouped together.
Este es un mensaje en varios idiomas. Dice lo mismo en
cada idioma. Si puede leerlo en un idioma, puede ignorar las otras
traducciones. Las otras traducciones pueden presentarse como archivos
adjuntos o agrupados.
"""
suben = EmailMessage()
# suben['Content-Language'] = 'en-GB'
suben['Content-Translation-Type'] = 'original'
# suben['Content-Disposition'] = 'inline' # redundant?
suben['Subject'] = 'Example of a message in Spanish and English'
suben.set_content("Hello, this message content is provided in your language.")
suben.add.header('Content-Language', 'en-GB')
suben.add_header('Content-Disposition', 'inline')
subes = EmailMessage()
# subes['Content-Language'] = 'es-ES'
subes['Content-Translation-Type'] = 'human'
# subes['Content-Disposition'] = 'inline' # redundant?
subes['Subject'] = 'Ejemplo práctico de mensaje en español e inglés'
subes.set_content("Hola, el contenido de este mensaje esta disponible en su idioma.")
subes.add_header('Content-Language', 'es-ES')
subes.add_header('Content-Disposition', 'inline')
msg.add_attachment(suben)
msg.add_attachment(subes)
msg.replace_header('Content-type', 'multipart/multilingual')
这大体上是基于 https://docs.python.org/3/library/email.examples.html 中的示例,并对这种相当不寻常的多部分类型进行了一些调整。
Demo: https://ideone.com/T0AonQ 显示第一个set_content 的内容被删除;如果你想支持它,以不同的方式添加它(我猜是另一个附件)应该很简单。
如演示所示,您可以使用msg.as_string() 检查生成消息的来源,并最终使用smtplib.send_message(msg) 发送。
我不知道电子邮件客户端在实践中对这种结构的支持程度(如果有的话)。
这使用了 Python 3.6 中经过大修的 EmailMessage 类。如果您使用的是旧版本,则在 3.3 中引入了此界面 - 但未记录在案;旧版本仍然必须使用旧的 email.message.Message() 类,但实际上,您会想要升级。