Skip to content

POP3 Utilities

pop3.pop3_utils

format_responses(responses)

Format the raw responses into a structured format for use in the application.

This function takes a dictionary of raw responses, typically from a POP3 server or similar service, and restructures them into a more accessible format.

Parameters:

Name Type Description Default
responses dict

The raw responses dictionary.

required

Returns:

Name Type Description
dict

A formatted dictionary where each key-value pair represents a code and its corresponding description.

Source code in src/pop3/pop3_utils.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def format_responses(responses):
    """
    Format the raw responses into a structured format for use in the application.

    This function takes a dictionary of raw responses, typically from a POP3 server or similar service,
    and restructures them into a more accessible format.

    Args:
        responses (dict): The raw responses dictionary.

    Returns:
        dict: A formatted dictionary where each key-value pair represents a code and its corresponding description.
    """
    if isinstance(responses, dict):
        formatted_responses = {}
        for item in responses.get("POP3_Responses", []):
            code = item.get("code")
            descriptions = item.get("descriptions", {})
            for key, description in descriptions.items():
                formatted_responses[f"{code} {key}"] = f"{code} {description}"
        return formatted_responses
    else:
        logger.error(f"Unexpected responses format: {responses}")
        return {}

generate_email_headers(email_body)

Generate synthetic email headers for a given email body.

This function creates fake email headers including fields such as 'Received', 'Message-ID', 'Date', 'From', and 'To', using random values for IP addresses and IDs. It simulates the email metadata.

Parameters:

Name Type Description Default
email_body dict

The body of the email for which headers are to be generated.

required

Returns:

Name Type Description
str

A string containing the generated email headers.

Source code in src/pop3/pop3_utils.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def generate_email_headers(email_body):
    """
    Generate synthetic email headers for a given email body.

    This function creates fake email headers including fields such as 'Received', 'Message-ID', 'Date',
    'From', and 'To', using random values for IP addresses and IDs. It simulates the email metadata.

    Args:
        email_body (dict): The body of the email for which headers are to be generated.

    Returns:
        str: A string containing the generated email headers.
    """
    random_ip = f"{random.randint(1, 255)}.{random.randint(0, 255)}.{random.randint(0, 255)}.{random.randint(0, 255)}"
    message_id = f"<{random.randint(1000000000, 9999999999)}.{''.join(random.choices(string.ascii_letters + string.digits, k=5))}@{domain_name}>"
    current_time = datetime.datetime.now()
    received_time = current_time - datetime.timedelta(hours=random.randint(10, 18))
    message_date_time = current_time - datetime.timedelta(hours=random.randint(5, 8))

    headers = (
        f"Received: from {random_ip} by {domain_name} (SMTPD) id {''.join(random.choices(string.ascii_letters + string.digits, k=10))}\n"
        f"Message-ID: {message_id}\n"
        f"Date: {message_date_time.strftime('%a, %d %b %Y %H:%M:%S %z')}\n"
        f"From: {'unknown@domain.com'}\n"
        f"To: {'recipient@domain.com'}\n"
        f"Subject: {'No Subject'}\n"
    )
    return headers

load_emails()

Load email data from predefined JSON files and prepare it for further processing.

This function checks specific JSON files for email data, extracts the contents, and formats them into a structure suitable for use within the application. It includes email headers, body, and size.

Returns:

Name Type Description
list

A list of dictionaries, each containing the email headers, body, full content, and size in bytes.

Source code in src/pop3/pop3_utils.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def load_emails():
    """
    Load email data from predefined JSON files and prepare it for further processing.

    This function checks specific JSON files for email data, extracts the contents, and formats them
    into a structure suitable for use within the application. It includes email headers, body, and size.

    Returns:
        list: A list of dictionaries, each containing the email headers, body, full content, and size in bytes.
    """
    email_files = [
        "files/email_email1.json",
        "files/email_email2.json",
        "files/email_email3.json"
    ]
    emails = []
    debug = config.getboolean('server', 'debug', fallback=False)
    if debug:
        logger.debug(f"Checking for email files in directory. Total files to check: {len(email_files)}")
    for email_file in email_files:
        if os.path.exists(email_file):
            if debug:
                logger.debug(f"Found email file: {email_file}")
            try:
                with open(email_file, 'r') as f:
                    email = json.load(f)
                    email_size = len(email.get("body", "").encode('utf-8'))
                    email_headers = generate_email_headers(email)
                    email_content = f"{email_headers}\n\n{email.get('body', '')}"
                    emails.append({
                        'headers': email_headers,
                        'body': email.get("body", ""),
                        'content': email_content,
                        'size': len(email_content.encode('utf-8'))
                    })
                    if debug:
                        logger.debug(f"Email file {email_file} size: {email_size} bytes")
            except Exception as e:
                logger.error(f"Error reading email file {email_file}: {e}")
        else:
            if debug:
                logger.debug(f"Email file not found: {email_file}")
    if debug:
        logger.debug(f"Total emails loaded: {len(emails)}")
    return emails

log_interaction(ip, command, response)

Log interactions between the client and the server.

This function logs the IP address of the client, the command sent, and the server's response.

Parameters:

Name Type Description Default
ip str

The IP address of the client.

required
command str

The command issued by the client.

required
response str

The response from the server.

required
Source code in src/pop3/pop3_utils.py
110
111
112
113
114
115
116
117
118
119
120
121
def log_interaction(ip, command, response):
    """
    Log interactions between the client and the server.

    This function logs the IP address of the client, the command sent, and the server's response.

    Args:
        ip (str): The IP address of the client.
        command (str): The command issued by the client.
        response (str): The response from the server.
    """
    logger.info(f"IP: {ip}, Command: {command}, Response: {response}")