在发送附件的电子邮件后如何关闭文件?
我有一个循环,该循环在电子邮件列表中向人们发送带有附件的电子邮件。问题是,当涉及到列表中的最后一个人时,我在电子邮件中附加的文件仍然保留在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就像您使用
Open()
打开文件一样,您需要使用CLOSE()
将其关闭如
attactment.close()
。或者,更好的是,使用上下文管理器:上下文管理器保证,用块在
之外关闭文件。
Just like you open a file with
open()
you need to close it withclose()
As in
attachment.close()
. Or, even better, use context manager:Context managers guarantee that file will be closed outside of the
with
block.