Search code examples
pythonpython-3.xmimesmtplib

How to send multiple e-mails at once with one xlsx file attachment each?


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:

  • the first email with 1 file attached
  • the second one with 2 files attached
  • the third one with 3 files attached

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

Solution

  • 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)
        ...