Home > database >  List Index is not returning values
List Index is not returning values

Time:12-03

I'm using Win32com in Python to access my Outlook emails, and I'm searching for a case number within the subject line of my emails, using regex.

For example, an email subject line may read Hisenburg CASE# 0039484. I have at least 30 emails like this.

Here is my code:

import pandas as pd, os
from pandas import DataFrame as df
import win32com.client as client
import time, datetime, smtplib, imaplib, pathlib, re

outlook = client.Dispatch('Outlook.Application')
namespace = outlook.GetNameSpace('MAPI')
account = namespace.Folders['[email protected]']
inbox = account.Folders['Inbox']
ap = inbox.Folders['Dean Brown']

pattern = re.compile(r'CASE# \d\d\d\d\d\d\d')
for x in message.items:
    b = re.findall(pattern, x.Subject)
    c = []
    for y in range(len(b)):
        c.append(b[y])
        print(c)

When I type c to get an item in the list, I get the following error: TypeError: 'NoneType' object is not subscriptable

If I type c[1] I get the following error: IndexError: list index out of range

Why would I receive this error when my results (c) populates 30 Numbers? Is there a way to populate the contents of email? How can I fix this?

CodePudding user response:

You get the error IndexError: list index out of range because you are starting a loop:

for y in range(len(b)):

Then when you have added the first item to the array, you ask directly after it for the second item in the array using c[1] which does not exist yet.

c.append(b[y])
print(c[1])

If you want to get the first item, you can shorten the indenting one step to the left and use c[0] or c[1] depending on the available results in the list.

Note that you don't have to do the looping mechanism.

You can use re.findall directly to return a list of strings.

c = re.findall(r"CASE# \d{7}", x.Subject)

CodePudding user response:

I was able to find a solution. The contents from my email were not populating and I solved the problem using this code after the c.append(b[y]):

    for y in range(len(b)):
        c.append(b[y])
        with open('Case_File ' today '.txt', 'a') as Case_File:
            Case_File.write('%s\n'%c)

This helped to send the appending values to a file which I was able to access and see all of my case numbers.

  • Related