私の目的は、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"