发送带附件的邮件后如何关闭文件?

How to close the file after sending emails with an attachment?

我有一个循环,可以将带有附件的电子邮件发送给电子邮件列表中的人。问题是,当涉及到列表中的最后一个人时,我在电子邮件中附加的文件仍然在 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)

不知怎么的,我需要在最后放一个参数来关闭文件,但我不知道该怎么做。

就像您使用 open() 打开文件一样,您需要使用 close() 关闭它 如 attachment.close()。或者,更好的是,使用上下文管理器:

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

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