[Tutor] I need to ignore an error let the script continue to run

Jim jf_byrnes at comcast.net
Mon May 4 22:41:04 EDT 2020


I ended up writing the program that lets me view parts of an email 
header in a pop up window without opening the message. It worked great 
until I received an email with a header that did not contain all the 
items I was trying to retrieve.

The parse_header function processes the data and passes it on to another 
part of the script to display it. In the header I am working with there 
is no 'Recepient username' in the header.I need a way to ignore any 
missing keys and process the ones that are there.

It seems try/except will not process the keys after the missing one.

I looked at something like dict.get(key, 'blank') but I can't figure out 
how to handle these two cases:

'Recepient username: ' + header['to'].addresses[0].username+'\n',
'Sender name: ' + header['from'].addresses[0].display_name

They don't look like keys, but they do resolve to the info I want if it 
is in the header.

Here is the function:

def parse_header(msg):
     with open('/home/jfb/' + email_msg, 'rb') as fp:
         header = BytesParser(policy=default).parse(fp)
         #  Now the header items can be accessed as a dictionary:
     try:
         headers = ['To: ' + header['to']+'\n' ,
         'From: ' + header['from']+'\n',
         'Subject: ' + header['subject']+'\n',
         'Return-Path: ' + header['return-path']+'\n' ,
         #This does not exist in some headers
         'Recepient username: ' + 
header['to'].addresses[0].username+'\n',
         'Sender name: ' + header['from'].addresses[0].display_name
         ]
         msg_header = []

         for item in headers:
             msg_header.append(item)

     except IndexError as error:
         print(error)
     # ~ except:
         # ~ pass
     return msg_header

This is the output if the username line is commented out:

To: undisclosed-recipients:;
From: Admin <williamsevanotty0147 at gmail.com>
Subject: restore
Return-Path: <williamsevanotty0147 at gmail.com>
Sender name: Admin

Any help appreciated,

Jim



More information about the Tutor mailing list