I have a section of code that pickles an object and then attaches the file to an email. My code looks like this:
# 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()
This works, but I end up with the my_obj.obj file still in the working directory. I could just delete the file after the code executes, but that seems ugly. Is there a way to execute this without creating an intermediate my_obj.obj file?
Instead of dump
use dumps
, it will return the serialized object as a string:
>>> str_obj = pickle.dumps([1,2,3])
>>> str_obj
'(lp0\nI1\naI2\naI3\na.'