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

seg*_*aba 0 python email-attachments file-in-use

我有一个循环,它向电子邮件列表中的人员发送带有附件的电子邮件。问题是,当涉及到列表中的最后一个人时,我在电子邮件中附加的文件仍然保持在 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)
Run Code Online (Sandbox Code Playgroud)

不知何故,我需要在末尾添加一个参数来关闭文件,但我不知道该怎么做。

mat*_*cja 5

就像您打开一个文件一样,您需要使用 As 来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
Run Code Online (Sandbox Code Playgroud)

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