Skip to content

Instantly share code, notes, and snippets.

@jaybo
Created February 15, 2021 09:49
Show Gist options
  • Save jaybo/3c2cbe65e1372f0fb58c7c197c29cfa7 to your computer and use it in GitHub Desktop.
Save jaybo/3c2cbe65e1372f0fb58c7c197c29cfa7 to your computer and use it in GitHub Desktop.
Extract Sender ID from Email Headers
import imaplib
import re
gmail = False
if gmail:
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('user', 'password')
mail.select('"[Gmail]/All Mail"')
else:
mail = imaplib.IMAP4_SSL('outlook.office365.com')
mail.login('user', 'password')
mail.select('"Inbox"')
# see all available folders
folder=mail.list()
print (folder)
#Search for all UIDs first
result,data=mail.uid('search',None,'ALL')
uids=data[0].split()
the_list = []
count = 0
#Loop through each uid to fetch headers
for uid in uids:
result,data=mail.uid('fetch',uid,'(RFC822.HEADER)')
# filter out just the 'sender IP is X.X.X.X;
full_header = data[0][1].decode("utf-8")
print(full_header)
just_sender = re.findall("sender IP.*?;", full_header)
the_list.append(just_sender)
count = count + 1
# if count == 3:
# break
# write the_list to output.txt
with open("output.txt", 'w') as file_handler:
for item in the_list:
file_handler.write("{}\n".format(item))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment