Vlad Buculei
Vlad Buculei

Reputation: 15

Move email to folder if more than one partial strings found in email subject

  1. I have a list containing Folder Names at the Outlook level ['fried chicken'; "boiled pasta"; "baked potatoes"], folders exist and are empty.
    The elements are strings that are combinations of two words example "fried chicken".

  2. I search the Inbox and if the message.subject matches one of the elements in the list move that email to the folder.
    Example: Email subject is "How fried is the chicken" or "I like my potatoes to be baked". It is not string in string exactly so my message.Move call doesn't find anything relevant.

Below is the "code".

alerts_folder = root_folder.Folders[folder_name_selected]
messages = alerts_folder.Items
z=messages.Count
message = messages.GetLast()
for message in list(messages):
    name = str(message.subject).lower()
    
`   #message = messages.GetPrevious()
    for y in top5:
        if all(x in name for x in y.split()):
            #print(str(name))
            #print("Email " + name + " goes into folder " + alerts_folder[y])
            name_of_selected_folder = str(y)
            final_destination = alerts_folder.Folders[name_of_selected_folder]
            #print("Email " + name + " goes into folder " + name_of_selected_folder)
            message.Move(final_destination)
            #message.Move(name_of_selected_folder)

Upvotes: 0

Views: 340

Answers (2)

dsanatomy
dsanatomy

Reputation: 533

Try:

for message in messages:
    name = str(message.subject)
    message = messages.GetPrevious()
    for y in list:
        if any(x in name for x in y.split()):
            print(str(name))
            #print("Email " + name + " goes into folder " + alerts_folder[list])
            message.Move(alerts_folder.Folders[list])

The code above firstly iterates over list and then splits every element in a list (as each element is a string of two words).

Upvotes: 1

Nja
Nja

Reputation: 489

I think the problem is due to the fact that x in if any(x in name for x in list) is the entire folder name.

If you're message subject is "fried chicken tasty" the code will match for the folder "fried chicken" but not for "fried chicken".

You can try with this code:

subject = "How fried is the chicken"
folders = ['fried chicken', 'boiled pasta', 'baked potatoes']
for folder in folders:
      keywords = folder.split()
      any(keyword in subject for keyword in keywords)

output will be:

True
False
False

note that this will work also for a partial subject matching like:

subject2 = "chicken tasty"

that is it will return true if only a folder keyword is in the subject string.

consider using all() function istead of any() to require all the keywords in folder names to be in the subject

for folder in folders:
    keywords = folder.split()
    all(keyword in subject for keyword in keywords)

Upvotes: 0

Related Questions