Home > front end >  Attach all files to outlook email
Attach all files to outlook email

Time:12-28

I want to attach files to an email that have varying names since the sender sends them this way.

All of the files are in a single folder, so I want to be able to attach said files, but cannot do a single specific file path because the name of the file varies.

Here's the code I am using to create the email, but I'm not sure on how to attach the files.

import win32com.client as win32

# Generates the Email for the file to be sent
outlook = win32.Dispatch('outlook.application')

mail = outlook.CreateItem(0)
mail.To = "[email protected]; [email protected];"
mail.CC = "[email protected]"
mail.Subject = 'Here are the requested files'
mail.Body = ''
mail.HTMLBody = (r"""Hello Team, <br><br>
    
    Hope you are doing well, please find attached the requested files. <br><br>

    """ 

#To attach a file to the email (optional):
attachment  = 
mail.Attachments.Add(str(attachment))

mail.Display(True)

I'm missing a way to attach the files to the email. If anyone could help, that'd be great. Thanks!

CodePudding user response:

Example

import os
import win32com.client


def attach_all_files(outlook, path):
    mail = outlook.CreateItem(0)
    mail.To = "[email protected]"
    mail.Subject = 'Here are the requested files'

    mail.HTMLBody = """ Hello Team, <br><br>
                        Hope you are doing well, 
                        please find attached the requested files. <br><br>
                    """

    # iterate over dir and check for files only
    for file in os.listdir(path):
        attachment = os.path.join(path, file)
        if os.path.isfile(attachment):
            print(attachment)
            mail.Attachments.Add(attachment)

    mail.Display()


if __name__ == "__main__":
    outlook = win32com.client.Dispatch("Outlook.Application")
    attach_all_files(outlook, r"D:\test")
  • Related