Python:通过电子邮件发送没有中间文件的pickle对象

时间:2013-06-01 16:45:25

标签: python email attachment pickle smtplib

我有一段代码来挑选一个对象,然后将该文件附加到一封电子邮件中。我的代码如下所示:

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

2 个答案:

答案 0 :(得分:2)

而不是dump使用dumps,它将序列化对象作为字符串返回:

>>> str_obj = pickle.dumps([1,2,3])
>>> str_obj
'(lp0\nI1\naI2\naI3\na.'

答案 1 :(得分:0)

对我有用的是:

from email.mime.application import MIMEApplication

attachment = MIMEApplication(pkl.dumps(data))
attachment.add_header('Content-Disposition', 'attachment', filename="data.pkl")
msg.attach(attachment)
相关问题