我有一段代码可以腌制一个对象,然后将文件附加到电子邮件中。我的代码如下所示:
# create message
msg = MIMEMultipart('alternative')
# generate a pickled object
fh = open('my_obj.obj', 'wb')
pickle.dump(my_obj, fh)
# attach the object file
filename = 'my_obj.obj'
f = file(filename)
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
# add content to log message
msg['Subject'] = "This is the subject"
msg['From'] = fromaddr
body = """This is the body of the message"""
content = MIMEText(body, 'plain')
msg.attach(content)
# email the message
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddr, msg.as_string())
server.quit()
这可行,但我最终得到的 my_obj.obj 文件仍在工作目录中。我可以在代码执行后删除文件,但这看起来很难看。有没有办法在不创建中间 my_obj.obj 文件的情况下执行此操作?