为什么在Python中向电子邮件头添加键会导致格式错误?

2024-10-03 04:39:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python来自动化我必须发送的电子邮件,并且我正在基于email package示例(第六个)和this tutorial构建代码,以便使用SMTP创建安全连接。简化代码如下所示:

import smtplib
import ssl
from getpass import getpass
from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

port = 465
strPass = getpass('Type password: ')

msg = EmailMessage()
msg['Subject'] = 'Title'
msg['From'] = Address('Name1', 'name1', 'example.com')
msg['To'] = Address('Name2', 'name2', 'example.com')
msg['Cc'] = Address('Name3', 'name3', 'example.com')
msg.set_content('somestringplain')

asparagus_cid = make_msgid()
msg.add_alternative('''\
<html>
    <head></head>
    <body>
        <p>somestringhtml</p>
        <img src='cid:{asparagus_cid}' />
    </body>
</html>
'''.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')

with open('./someimage.png', 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'png', cid=asparagus_cid)

context = ssl.create_default_context()

with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

with smtplib.SMTP_SSL('smtp.gmail.com', port, context=context) as server:
    server.login('name1@example.com', strPass)
    server.send_message(msg)

代码的工作方式是成功地发送邮件,但它破坏了预期的发送格式。以下是正文的格式:

MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="===============1615846942694093528=="

--===============1615846942694093528==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

somestringplain

--===============1615846942694093528==
MIME-Version: 1.0
Content-Type: multipart/related;
 boundary="===============2463145904749303214=="

--===============2463145904749303214==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: quoted-printable

<html>
    <head></head>
    <body>
        <p>somestringhtml</p>
        <img src='cid:156235339922.24812.3941539910138014756@MYPC' />
    </body>
</html>

...

我发现问题在于为电子邮件定义一个复写副本。如果删除带有msg['Cc']位的行,邮件将以正确的HTML格式发送

为什么会发生这种情况,如何使它工作,因为我需要为我的任务设置一个复写副本

如果相关,实际的客户是一个G套件帐户


Tags: fromimportcomimgaddressexampleemailhtml