Python email automation

Hello
I’m not sure if I can post python related query or not.
If yes pls reply.
This is an email automation related query.
I should download attachments from outlook from a specific sender on a daily basis. I wrote a code but it’s not accessing the outlook.
Can someone help me pls

Hey @shama93
I’m not python expert but I did something similar a while ago.
You can try to modify it to suit your requirements.

import win32com.client
import os

# Set up the Outlook client
# This line creates a connection to the Outlook application using the win32com library.
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

# Access the Inbox folder
# '6' refers to the Inbox folder. Outlook folders are identified by specific numbers.
inbox = outlook.GetDefaultFolder(6)

# Define the sender's email address and the path to save attachments
# Email address of the sender whose emails' attachments you want to download.
sender_email = "sender@example.com"
# Path where you want to save the downloaded attachments.
attachment_dir = r"C:\path\to\save\attachments"

# This block checks if the specified path for saving attachments exists. If not, it creates the directory.
if not os.path.exists(attachment_dir):
    os.makedirs(attachment_dir)

# This counter keeps track of the number of processed emails.
message_count = 0

# The loop goes through the emails in reverse order (newest first).
for message in reversed(inbox.Items):
    # Stop after processing 30 messages
    if message_count >= 30:
        break

    try:
        # Check if the message is an email and is unread
        # '43' represents olMail. This checks if the message is an email and unread.
        if message.Class == 43 and message.UnRead:
            # Check if the email is from the specified sender
            if message.SenderEmailAddress == sender_email:
                # Iterate through and save each attachment
                for attachment in message.Attachments:
                    # Save each attachment to the specified directory
                    attachment.SaveAsFile(os.path.join(attachment_dir, attachment.FileName))
                    print(f"Saved attachment: {attachment.FileName}")
                # Mark the email as read
                message.UnRead = False
                # Save the changes to the message
                message.Save()
                # Increment the message counter
                message_count += 1
    except AttributeError as error:
        # Print any errors encountered
        print(f"Error: {error}")

print("Process completed.")

This code is running but not downloading any attachments

Hi @shama93,

import win32com.client
import re
import datetime

# Set up connection to Outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items

# Set conditions
sender_email = 'Email ID'
subject_line = 'SUbject Line'
download_folder = r'DOwnload Path'

# Set the specific date to search for emails


message = messages.GetFirst()

while message:
    try:
        current_sender = str(message.SenderEmailAddress).lower()
        current_subject = str(message.Subject).lower()
       

        # Condition: Specific sender, subject, and the specified date
        if (current_sender == sender_email.lower() and
                current_subject == subject_line.lower()):

            print(f"Subject: {current_subject}")  # Verify the subject
            print(f"Sender: {current_sender}")  # Verify the sender

            attachments = message.Attachments
            for attachment in attachments:
                attachment_name = str(attachment.FileName)
                attachment.SaveASFile(download_folder + '\\' + attachment_name)
                print(f"Downloaded: {attachment_name}")
        
        message = messages.GetNext()
    except Exception as e:
        print(f"An error occurred: {e}")
        message = messages.GetNext()

Try above code, hope it works for you :slight_smile:

Regards,
Vinit Mhatre

Thank for your reply, but neither the error nor the output

Could you please share with me your email data Screenshot?

@shama93
I tested it on my environment and it is working fine.
Are you using inbox or any subfolder in mailbox?

I am using Inbox itself