在发送附件的电子邮件后如何关闭文件?

发布于 2025-01-26 09:16:16 字数 791 浏览 2 评论 0原文

我有一个循环,该循环在电子邮件列表中向人们发送带有附件的电子邮件。问题是,当涉及到列表中的最后一个人时,我在电子邮件中附加的文件仍然保留在Windows中。

for index, row in f.iterrows():
    print (row["ManagerEmail"]+row["filename"])
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['Subject'] = row["filename"] + f" Sales Letter"
    msg.attach(MIMEText(body, 'plain'))
    filename = row["filename"]
    toaddr = row["ManagerEmail"]
    attachment = open(row["filepath"], "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
    msg.attach(part)
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)

以某种方式,我需要在末尾放置一个参数才能关闭文件,但我不知道该怎么做。

I have a loop which sends email with an attachment to the people in emailing list. The problem is, when it comes to the last person in the list, the file I am attaching on email still stays as in use in Windows.

for index, row in f.iterrows():
    print (row["ManagerEmail"]+row["filename"])
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['Subject'] = row["filename"] + f" Sales Letter"
    msg.attach(MIMEText(body, 'plain'))
    filename = row["filename"]
    toaddr = row["ManagerEmail"]
    attachment = open(row["filepath"], "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
    msg.attach(part)
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)

Somehow I need to put a parameter at the end to close the file but I do not know how to do that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

有木有妳兜一样 2025-02-02 09:16:16

就像您使用Open()打开文件一样,您需要使用CLOSE()将其关闭
attactment.close()。或者,更好的是,使用上下文管理器:

with open(row["filepath"], "rb") as attachment:
   # Code that uses attachment file goes here
# Code that no longer uses that file goes here

上下文管理器保证,用块在之外关闭文件。

Just like you open a file with open() you need to close it with close()
As in attachment.close(). Or, even better, use context manager:

with open(row["filepath"], "rb") as attachment:
   # Code that uses attachment file goes here
# Code that no longer uses that file goes here

Context managers guarantee that file will be closed outside of the with block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文