我有自动发送电子邮件的代码,我想在电子邮件中添加图片,但实际路径是在电子邮件中发送的[重复]

问题描述 投票:0回答:1

所以,我有一个可以为我发送电子邮件的程序。 该程序的目标是让它按计划运行,并每 24 小时发送一次电子邮件,但首先我需要弄清楚如何将图像附加到发送的电子邮件中。 这是我到目前为止所拥有的:

import os
from email.message import EmailMessage
import ssl
import smtplib
email_sender = '[email protected]'
Password = 'app password'
email_receiver = '[email protected]'
subject = 'Message subject'
body = 'message body'
em = EmailMessage()
em['From'] = email_sender
em['To'] = email_receiver
em['Subject'] = subject
em.set_content(body)
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
        smtp.login(email_sender, Password)
        em.add_attachment('path to desired .jpg file', subtype = ".jpg", filename = ".jpg file name")
        smtp.sendmail(email_sender, email_receiver, em.as_string())

所以,我遇到的问题是,它会发送带有附件的电子邮件,但是当附件打开时,它只是图像从我的计算机获得的路径的打印输出,而不是图像本身。那么,如何将图片链接到电子邮件,而不仅仅是路径呢? 感谢您提供的任何帮助。

python email email-attachments
1个回答
0
投票

如果你想要内容,请传递内容:

        em.add_attachment(open('path to desired .jpg file', 'rb').read(), subtype = ".jpg", filename = ".jpg file name")

© www.soinside.com 2019 - 2024. All rights reserved.