I have this simple script that attaches a text file to an email in Python. When I run this script in IDLE it works fine. When I run it in Canopy Express however, I get this error: (The text.txt file is in the same directory as the python script)
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
C:\Program Files (x86)\Enthought\Canopy32\App\appdata\canopy-1.2.0.1610.win-x86\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
195 else:
196 filename = fname
--> 197 exec compile(scripttext, filename, 'exec') in glob, loc
198 else:
199 def execfile(fname, *where):
C:\Users\499293\Desktop\Project Folder\attachex.py in <module>()
7
8 # Read a file and encode it into base64 format
----> 9 fo = open(filename, "rb")
10 filecontent = fo.read()
11 encodedcontent = base64.b64encode(filecontent) # base64
IOError: [Errno 2] No such file or directory: 'text.txt'
This is the code I am using:
#!/usr/bin/python
import smtplib
import base64
filename = "text.txt"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'me@work.com'
reciever = 'them@work.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('mailhost.work.com', 25)
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"
I don't really understand what the error means or why I am getting it using Canopy but not IDLE. (I just downloaded Canopy to take advantage of the built in matplotlib and numpy)
The fact that the file is in the same directory is not relevant - it has to be in the current working directory - iow the directory you're in when launching the script. Else you either need to pass the file's path as argument or compute a path from the script's location (which you can get from the __file__
magic variable).