0

我有一段代码可以腌制一个对象,然后将文件附加到电子邮件中。我的代码如下所示:

# 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 文件的情况下执行此操作?

4

2 回答 2

2

代替dumpuse dumps,它将序列化对象作为字符串返回:

>>> str_obj = pickle.dumps([1,2,3])
>>> str_obj
'(lp0\nI1\naI2\naI3\na.'
于 2013-06-01T16:53:53.310 回答
0

对我有用的是:

from email.mime.application import MIMEApplication

attachment = MIMEApplication(pkl.dumps(data))
attachment.add_header('Content-Disposition', 'attachment', filename="data.pkl")
msg.attach(attachment)
于 2017-10-09T13:27:52.603 回答