OneCompiler

Em

1642

import win32com.client
import os

Create an instance of the Outlook application

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
outlook_app = win32com.client.Dispatch("Outlook.Application") # Used for sending emails

Access the Inbox

inbox = outlook.GetDefaultFolder(6) # "6" refers to the Inbox

Define the desktop folder path to save the Excel attachment

desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
save_folder = os.path.join(desktop, "excel")

Create folder if it doesn't exist

if not os.path.exists(save_folder):
os.makedirs(save_folder)

Define the email address and subject line to look for

target_email = "[email protected]"
target_subject = "Specific Subject Line"

Path of the report file to send as a reply (Update with your file path)

report_file_path = os.path.join(desktop, "report_file.xlsx")

Get unread messages

unread_messages = inbox.Items.Restrict("[UnRead] = True")

Iterate over unread emails

for message in unread_messages:
# Check if the email is from the target sender and has the specific subject
if message.SenderEmailAddress == target_email and target_subject in message.Subject:
# Check for attachments
for attachment in message.Attachments:
# If the attachment is an Excel file (by extension)
if attachment.FileName.endswith(".xlsx") or attachment.FileName.endswith(".xls"):
# Save the attachment to the folder
attachment.SaveAsFile(os.path.join(save_folder, attachment.FileName))
print(f"Saved {attachment.FileName} to {save_folder}")

    # After processing the message, send a reply email with the report attachment
    reply = message.Reply()
    reply.Subject = "Your Report"  # Customize subject line
    reply.Body = "Please find the report attached."  # Customize the email body

    # Attach the report file
    attachment = reply.Attachments.Add(report_file_path)

    # Send the email
    reply.Send()
    print(f"Report sent to {message.SenderEmailAddress}")

print("Script completed.")