Python 2.7 smtplib如何发送错误13权限被拒绝的附件?

时间:2016-09-26 20:39:09

标签: python python-2.7 mime-types mime smtplib

希望你很好。我在Windows 7上使用python 2.7和PyCharm以及它的新功能。 我尝试发送带附件的电子邮件但收到错误:
IOError:[Errno 13]权限被拒绝:' C:\ Users \ Myname \ Desktop'这是我的代码:

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

fromaddr = "mail@gmail.com"
toaddr = "mail@gmail.com"

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Something bla bla bla"

body = "Something bla bla bla"

msg.attach(MIMEText(body, 'plain'))

filename = "CV.txt"
attachment = open("C:\Users\MyName\Desktop","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.starttls()
server.login(fromaddr, "PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

我阅读了其他文章,最常见的问题似乎是没有足够的许可,但我是管理员。无论如何,如果是这样的话,我需要一步一步地做到这一点才能实现它?或者是否存在与许可无关的其他问题? 提前致谢。 最热烈的问候

1 个答案:

答案 0 :(得分:1)

您正在尝试将目录作为文件打开,您需要传递要打开的实际文件:

attachment =  open(r"C:\Users\MyName\Desktop\the_file")