Reputation: 47
I found this code from another website repository and its used to send emails using python and attach's a file as well. It encodes the file in to base64 brfore sending it. I've tested the code before using an '.xlsx' file and it was sent with out a problem. But now the program doesnt send it for some reason. The file is in the same folder as the code.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "FROM EMAIL"
toaddr = "TO EMAIL"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT"
body = "MESSAGE"
msg.attach(MIMEText(body, 'plain'))
filename = "05-11-2016 - Saturday.xlsx"
attachment = open("05-11-2016 - Saturday", "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()
When i run it ths is the error that is outputted:
line 21, in <module>
attachment = open("05-11-2016 - Saturday", "rb")
FileNotFoundError: [Errno 2] No such file or directory: '05-11-2016 - Saturday'
Any help would be appreciated.
Upvotes: 1
Views: 2523
Reputation: 63
I just ran your code using my credentials and made a small txt file in the same directory as the code to replicate your conditions. Here's what you need to modify:
filename = "ExplicitFileName.txt"
attachment = open("/USE/COMPLETE/PATH/TO/FILE/ExplicitFileName.txt", "rb")
Or as Ilja pointed out the DRY principle you could do it like this:
filename = "ExplicitFileName.txt"
attachment = open("/COMPLETE/PATH/TO/FILE/" + filename, "rb")
Both of these will work just fine.
Upvotes: 0
Reputation: 2114
you have defined filename
in the line above - so why don't you use it? :)
(you forgot the extension 'xlsx' in the open
statement)
You now have learned the usefullnes of the DRY-principle: http://wiki.c2.com/?DontRepeatYourself
By typing it twice, you can change the filename definition and not notice, that the open
uses another file...
Upvotes: 1