Search code examples
pythonoutlookattachmentwin32com

Python win32com outlook keeps removing the wrong attachment


I have a script that is supposed to forward certain emails bases on existence of a specific type of attachment, let's say .PDF. I already have it sorting the emails correctly and the forwarding is perfect. The only thing is, when I try to remove the said attachment it removes a different one. I am using the same for-loop to identify the attachments and it does recognize the one I want to remove but for some reason, the index (???) is not the same anymore and it removes a different one. Also, I already found out that when it removes on it automatically updates the attachment indexes

new_mail = message.Forward()
new_mail.To = '[email protected]'
attach_index=1

for attachment in attachments:        
        
        print("i can print the index correctly, and all the filename characteristic to select the one i want)

        if ***condition****:
            print('to remove...')
            new_mail.Attachments.Remove(attach_index)
        else:
            attach_index = attach_index+1

new_mail.Send()

in this particular case I have an email with a .pdf , a .txt and an image in the signature, that python also recognizes as an attachment. I keeps outputting "to remove...." on the correct one but removing another. What am I doing wrong? Please help


Solution

  • use Attachment.Delete instead of Attachments.Remove(index) - this way you won't have to deal with any indices.