Search code examples
pythonpython-2.7mime-typesmimesmtplib

Python 2.7 smtplib how to send attachment with Error 13 permission denied?


hope you are well. I'm using python 2.7 with PyCharm on a Windows 7 and new at it. I'm trying to send email with attachment but get error :
IOError: [Errno 13] Permission denied: 'C:\Users\Myname\Desktop' This is my code:

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()

I read the other articles and the most common problem seems to be to not have sufficent permission, however i am the Administrator. Anyhow if that were to be the case what i need to do exactlys step by step to get it going? or is there another problem not related to the permission? Thanks in advance. Warmest regards


Solution

  • You are trying to open a directory as a file, you need to pass the actual file you want to open:

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