我正在使用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 Suite帐户。