我的目标是使用 Python 向具有内嵌图像的 Gmail 用户发送电子邮件。href
由于图像的敏感性(来自我工作的数据),无法在线托管此图像,然后通过 a 链接到它。
我尝试将base64
版本编码为HTML
然后发送 th is HTML
,但众所周知这是行不通的。然后我注意到,在 Gmail 中,您可以将图像拖放到发送框中,它将在接收端内联显示。鉴于此,我尝试从 Python 发送一封电子邮件,并将图像作为附件。这在下面的代码中可以看到,但不幸的是图像没有内联显示。
那么我的问题是:如何发送图像以使其内联显示?
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
gmail_user = "user1@gmail.com"
gmail_pwd = "pass"
to = "user2@gmail.com"
subject = "Report"
text = "Picture report"
attach = 'TESTING.png'
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
当我手动将内联图像发送给自己时,这就是“原始电子邮件”的样子:
Content-Type: multipart/related; boundary=047d7bd761fe73e03304e7e02237
--047d7bd761fe73e03304e7e02237
Content-Type: multipart/alternative; boundary=047d7bd761fe73e03004e7e02236
--047d7bd761fe73e03004e7e02236
Content-Type: text/plain; charset=ISO-8859-1
[image: Inline images 1]
--047d7bd761fe73e03004e7e02236
Content-Type: text/html; charset=ISO-8859-1
<div dir="ltr"><img alt="Inline images 1" src="cid:ii_141810ee4ae92ac6" height="400" width="534"><br></div>
--047d7bd761fe73e03004e7e02236--
--047d7bd761fe73e03304e7e02237
Content-Type: image/png; name="Testing.png"
Content-Transfer-Encoding: base64
Content-ID: <ii_141810ee4ae92ac6>
X-Attachment-Id: ii_141810ee4ae92ac6
当我通过 Python 将它作为附件发送给自己时,情况就大不相同了:
Content-Type: multipart/mixed; boundary="===============6881579935569047077=="
MIME-Version: 1.0
(.... some stuff deleted here)
--===============6881579935569047077==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
See attachment for report.
--===============6881579935569047077==
Content-Type: application/octet-stream
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="TESTING.png"