Skip to main content

Email Id Extraction from Logs

Sample Log File

Save the logs in a file named sample_email_log.txt.

2023-10-22 12:01:23 INFO User 'admin' with email '[email protected]' logged in.
2023-10-22 12:05:45 WARNING Phishing email received from '[email protected]'.
2023-10-22 12:07:30 INFO User 'john_doe' with email '[email protected]' reported a suspicious email from '[email protected]'.
2023-10-22 12:09:15 ERROR Failed sending email to '[email protected]'.
2023-10-22 12:10:00 INFO User 'alice' with email '[email protected]' logged in.
2023-10-22 12:12:12 WARNING Phishing email received from '[email protected]'.

Python Code

Save the code in a file named extract_emails.py.

extract_emails.py
import re

# Define a function to extract email addresses from a log file
def extract_emails_from_log(log_file_path):
# Open the log file and read its content
with open(log_file_path, 'r') as file:
log_data = file.read()

# Use a regular expression to find all email addresses in the log data
email_ids = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', log_data)

# Return the list of extracted email addresses
return email_ids

# Call the function and print the extracted email addresses
emails = extract_emails_from_log('sample_email_log.txt')
print("Extracted Email Addresses:")
for email in emails:
print(email)