Python文件附件错误

时间:2016-04-07 23:20:37

标签: python python-3.x

我正在尝试在python中添加电子邮件附件,我不断收到错误:

IsADirectoryError:[Errno 21]是一个目录:'/ Users / myname / Desktop / Current Desktop / Folder'

这是我的代码:

file =  "myfile.pdf"
attachment = open("/Users/myname/Desktop/Current Desktop/Folder","rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload((file).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename=%s" % file)

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

我想你想要像

这样的东西
with open("/Users/myname/Desktop/Current Desktop/Folder/" + "myfile.pdf", "rb") as file: 

    part = MIMEBase('application', 'octet-stream')
    part.set_payload(file.read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename=%s" % file)