我想使用Python向一个有内嵌图片的Gmail用户发送邮件。由于这些图片涉及到我的工作数据,所以不可能将其托管在网上并通过href链接到它。
我已经尝试将base64版本编码成HTML,然后发送这个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"