Email Slicer Project (Code) in Python

← Back to Projects

Email Slicer in Python

About the project:This program will take an email address as input from you and then "slice" it into two main parts: the username and the domain.

This is a straightforward and useful tool for extracting information from email addresses.

How to use this Email Slicer:

  • Run the Python script.
  • It will prompt you to enter an email address.
  • Then, it will ask for the month (1-12, e.g., 7 for July).
  • After you enter an email, it will display the username and the domain separately.
  • You can keep entering email addresses to slice, or type q to quit the program.


Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# email_slicer.py

def slice_email():
    """
    Prompts the user for an email address and then slices it into
    the username and domain parts.
    """
    print("--- Python Email Slicer ---")

    while True:
        email_input = input("Enter an email address (or 'q' to quit): ").strip()

        if email_input.lower() == 'q':
            print("Exiting Email Slicer. Goodbye!")
            break

        # Check if the email contains an '@' symbol
        if '@' in email_input:
            # Split the email address at the '@' symbol
            # This creates a list, where the first element is the username
            # and the second element is the domain.
            parts = email_input.split('@')
            username = parts[0]
            domain = parts[1]

            print("\n--- Sliced Email ---")
            print(f"Username: {username}")
            print(f"Domain: {domain}")
            print("--------------------\n")
        else:
            print("Invalid email address. Please include an '@' symbol.")

# This ensures that slice_email() is called only when the script is executed directly.
if __name__ == "__main__":
    slice_email()





Below is another code snippet with Email Slicer Project to make it even more useful.

Below code will include:

More Robust Email Validation: The program will now perform a more thorough check to ensure the email format is generally valid (e.g., has a username, an @ symbol, and a domain with a dot).

Save Sliced Emails: You'll have the option to save the sliced email details (username and domain) to a JSON file.

View Saved Emails: A new menu option will allow you to view all the email addresses you've previously sliced and saved.




# email_slicer.py

import json
import os
from datetime import datetime

# File to store sliced email history
SLICED_EMAILS_FILE = "sliced_emails_history.json"

def validate_email(email):
    """
    Performs basic validation on the email address format.
    Returns True if valid, False otherwise.
    """
    if '@' not in email:
        return False, "Email must contain an '@' symbol."

    parts = email.split('@')
    username = parts[0]
    domain = parts[1]

    if not username:
        return False, "Username cannot be empty."
    
    if not domain:
        return False, "Domain cannot be empty."
    
    if '.' not in domain:
        return False, "Domain must contain a '.' (e.g., example.com)."
    
    # Basic check for multiple '@' symbols (though split handles it, it's good practice)
    if len(parts) > 2:
        return False, "Email contains multiple '@' symbols."

    return True, None # Email is considered valid

def save_sliced_email(username, domain):
    """
    Saves the sliced email details to a JSON file.
    """
    entry = {
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "username": username,
        "domain": domain
    }

    history = []
    if os.path.exists(SLICED_EMAILS_FILE):
        try:
            with open(SLICED_EMAILS_FILE, 'r') as f:
                history = json.load(f)
        except json.JSONDecodeError:
            print("Warning: Sliced emails history file is corrupted or empty. Starting new history.")
            history = []
    
    history.append(entry)

    with open(SLICED_EMAILS_FILE, 'w') as f:
        json.dump(history, f, indent=4)
    print("Sliced email saved to history.")

def view_sliced_emails():
    """
    Displays all previously sliced email entries from the JSON file.
    """
    if not os.path.exists(SLICED_EMAILS_FILE) or os.stat(SLICED_EMAILS_FILE).st_size == 0:
        print("\nNo sliced email history found yet.")
        return

    try:
        with open(SLICED_EMAILS_FILE, 'r') as f:
            history = json.load(f)
    except json.JSONDecodeError:
        print("Error: Could not read sliced emails history file. It might be corrupted.")
        return

    if not history:
        print("\nNo sliced email history found yet.")
        return

    print("\n--- Your Sliced Email History ---")
    for i, entry in enumerate(history):
        print(f"\nEntry {i+1}:")
        print(f"  Date/Time: {entry.get('timestamp', 'N/A')}")
        print(f"  Username: {entry.get('username', 'N/A')}")
        print(f"  Domain: {entry.get('domain', 'N/A')}")
    print("---------------------------------")

def main():
    """
    Main function for the Email Slicer, providing a menu for operations.
    """
    print("--- Python Email Slicer ---")

    while True:
        print("\nSelect an option:")
        print("1. Slice a New Email")
        print("2. View Sliced Email History")
        print("3. Quit")

        choice = input("Enter your choice (1, 2, or 3): ").strip()

        if choice == '3':
            print("Exiting Email Slicer. Goodbye!")
            break
        elif choice == '2':
            view_sliced_emails()
            continue
        elif choice == '1':
            email_input = input("Enter an email address: ").strip()
            
            is_valid, error_msg = validate_email(email_input)

            if is_valid:
                parts = email_input.split('@')
                username = parts[0]
                domain = parts[1]

                print("\n--- Sliced Email ---")
                print(f"Username: {username}")
                print(f"Domain: {domain}")
                print("--------------------\n")
                
                save_sliced_email(username, domain)
            else:
                print(f"Invalid email address: {error_msg}")
        else:
            print("Invalid choice. Please enter 1, 2, or 3.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()