I'm writing a Python script that searches for .XLSX files with a specific name in a directory and then sends e-mails with those files attached to them. If there are 3 XLSX files in that directory I want to send 3 e-mails, each with one of the files attached. What is happening with my code is that, in that example, it sends 3 e-mails:
I tried moving the file to another directory after its attachment to the e-mail message, but it didn't work. Here's the code:
for xlsxfile in glob.glob(os.path.join('.', 'START_OF_FILENAME_*.XLSX')):
xlsxpart = MIMEApplication(open(xlsxfile, 'rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename=xlsxfile[1:])
msg.attach(xlsxpart)
shutil.move(xlsxfile, './sent/'+xlsxfile[2:])
try:
client = smtplib.SMTP()
client.connect('XX.XXX.XX.XX', port=25)
client.sendmail(username, rcptlist, msg.as_string())
client.quit()
#...exception handling
for xlsxfile in glob.glob(os.path.join('.', 'START_OF_FILENAME_*.XLSX')):
...
msg.attach(xlsxpart)
...
In every iteration the current file is being added to the existing msg
object. By the time the loop gets to the third iteration, msg
already has the previous 2 files attached to it.
Instead, a new msg
object should be created every iteration:
for xlsxfile in glob.glob(os.path.join('.', 'START_OF_FILENAME_*.XLSX')):
...
msg = Message(...) # however you created msg before the loop
msg.attach(xlsxpart)
...