Email Manager In Python: Script Discussion & Guide

by Alex Johnson 51 views

In today's digital age, managing emails efficiently is crucial for both personal and professional productivity. This article dives into a Python script designed to help you manage your email credentials securely. We will explore the code, discuss its functionalities, and provide a comprehensive guide on how to use it. Whether you are a developer looking to enhance your Python skills or someone seeking a better way to organize your email information, this guide is for you.

Understanding the Email Manager Script

This Email Manager script, written in Python, is a simple yet effective tool for managing your email accounts. It allows you to add, remove, view, and securely save your email credentials. The script utilizes several Python libraries, including re for regular expressions, os for operating system interactions, time for time-related tasks, json for handling JSON data, and getpass for secure password input. Let's break down the script's structure and functionalities.

Core Components of the Email Manager

The script is built around the EmailManager class, which encapsulates the core functionalities. Here’s a detailed look at the class and its methods:

  1. __init__(self): Initialization

    The constructor initializes the EmailManager. It prints a welcome message and loads email data from a JSON file (EmailDATA.json) if it exists. If the file doesn't exist, it initializes an empty list to store email data. The use of try-except blocks ensures that file operations are handled gracefully, preventing the program from crashing due to file-related issues. This method is crucial for setting up the application state and ensuring that existing data is loaded.

    def __init__(self):
        print(
            """ 
    =========
    Email Manager
    =========
                  """
        )
        self.EMAILDATA = []
        self.load()
    
  2. menu(self): Displaying the Menu

    The menu method displays the main menu options to the user. These options include adding an email, removing an email, viewing emails, saving data, and exiting the application. The menu is presented in a clear and numbered format, making it easy for the user to select an option. This method is the primary interface for user interaction, guiding the user through the available actions.

    def menu(self):
        self.menuItems = [
            "Add Email",
            "remove Email",
            "View Emails",
            "Save Data",
            "Exit",
        ]
        print("\t\tMain Menu")
        for i, o in enumerate(self.menuItems, start=1):
            print(f"\t\t[ {i} ].{o}")
    
  3. load(self): Loading Email Data

    The load method attempts to load email data from the EmailDATA.json file. It uses a try-except block to handle potential file-related errors, such as the file not existing or not being found. If the file is successfully loaded, the email data is stored in the self.EMAILDATA list. If any error occurs during the file loading process, an appropriate error message is printed. This method ensures that the application can resume its previous state by loading saved email data.

    def load(self):
        try:
            if os.path.exists(r"Projects\database\EmailDATA.json"):
                with open(r"Projects\database\EmailDATA.json", "r") as file:
                    self.EMAILDATA = json.load(file)
            else:
                self.EMAILDATA = []
        except FileExistsError:
            print(FileExistsError("file is not exists!!!"))
        except FileNotFoundError:
            print(FileNotFoundError("file path not found!!!"))
        except Exception as error2:
            print(error2)
    
  4. save(self): Saving Email Data

    The save method saves the email data stored in self.EMAILDATA to the EmailDATA.json file. This method uses the json.dump function to serialize the Python list into JSON format and write it to the file. The indent=3 parameter ensures that the JSON data is formatted with an indentation of 3 spaces, making it human-readable. Similar to the load method, it uses a try-except block to handle potential file-related errors. This method is crucial for persisting email data, ensuring that it is not lost when the application is closed.

    def save(self):
        try:
            with open(r"Projects\database\EmailDATA.json", "w") as file:
                json.dump(self.EMAILDATA, file, indent=3)
                print("Email Data is Securely Saves in Database")
    
        except FileNotFoundError:
            print(FileNotFoundError("file path not found!!!"))
        except Exception as error3:
            print(error3)
    
  5. add(self): Adding a New Email

    The add method allows the user to add a new email to the managed list. It prompts the user for the email address, password, and purpose of the email. The method performs several validations, including checking the email format using a regular expression (self.emailpattern) and ensuring the password meets certain criteria (minimum length of 8 characters and presence of both uppercase and lowercase letters). If the email is already present in the database, a message is displayed, and the addition is aborted. If the validations pass, the new email data is added to the self.EMAILDATA list. This method ensures that only valid and unique email credentials are added to the database.

    def add(self):
        self.takeemail = input("Enter Your Email (e.g. name123@gmail.com)\t")
        self.takepassword = gt.getpass("Enter Your password\t")
        self.takepurpose = input(
            "Enter the purpose of this Email (e.g. Education,Bussiness etc)\t"
        )
        self.emailpattern = r"^[\w\.-]+@[\w\.-]+\.(com|org|net|pk){{content}}quot;
    
        self.passwordpattern = all(
            [
                len(self.takepassword) >= 8,
                re.search(r"[A-Z]", self.takepassword),
                re.search(r"[a-z]", self.takepassword),
            ]
        )
        try:
            if not re.match(self.emailpattern, self.takeemail):
                print("❌ Invalid Email")
            elif not self.passwordpattern:
                print("❌ Invalid password")
            else:
                for record in self.EMAILDATA:
                    if record["Email"] == self.takeemail:
                        print("Email is already present in database!!!")
                        return None
    
                print("βœ… Valid Email\nβœ… Strong Password Entered")
                self.tememailDATA = {
                    "Email": self.takeemail,
                    "Password": self.takepassword,
                    "Purpose": self.takepurpose,
                }
                self.EMAILDATA.append(self.tememailDATA)
                print(
                    "πŸ“Œ Email stored in memory (not saved yet). Use option 3 to save."
                )
                # self.save()
        except TypeError:
            print(TypeError("invalid type password or email"))
        except Exception as error:
            print(error)
    
  6. rm(self): Removing an Email

    The rm method allows the user to remove an email from the managed list. It prompts the user for the email to delete and then iterates through the self.EMAILDATA list to find a matching record. If a match is found, the email is removed from the list. If no match is found, a message is displayed indicating that the email was not found. This method provides a way to keep the email list up-to-date by removing obsolete or unwanted entries.

    def rm(self):
        self.delteEmail = input("Enter the Email to Delete:\t").strip()
        try:
            if not self.EMAILDATA:
                print("No Emails Data is found!!!")
        except Exception as error6:
            print(error6)
        try:
            for record in self.EMAILDATA:
                if (
                    record["Email"] == self.delteEmail
                    or record["Password"] == self.delteEmail
                    or record["Purpose"] == self.delteEmail
                ):
                    self.EMAILDATA.remove(record)
                    print(f"{self.delteEmail} is Successfully!!!")
                    return
            print(f"{self.delteEmail} is not found yet!!!")
        except Exception as error5:
            print(error5)
    
  7. view(self): Viewing Emails

    The view method displays the list of saved emails to the user. It iterates through the self.EMAILDATA list and prints the email, password, and purpose for each record. If the list is empty, a message is displayed indicating that no email data is found in the database. This method allows the user to review the stored email credentials.

    def view(self):
        print("\nSaved Emails list:")
        if not self.EMAILDATA:
            print("No Email Data found in Database!!!")
            return None
    
        for w, q in enumerate(self.EMAILDATA, start=1):
            print(
                f"{w} Email: {q['Email']}\nPassword: {q['Password']}\n Purpose: {q['Purpose']}"
            )
    
  8. checkmenuoptions(self): Handling Menu Options

    The checkmenuoptions method presents the main menu to the user and handles their input. It continuously loops, displaying the menu and prompting the user for an option. Based on the user's input, it calls the appropriate method (e.g., add, rm, view, save). The loop continues until the user selects the exit option. Input validation is performed to ensure the user enters a valid menu option. This method is the main control loop of the application, driving the user interaction.

    def checkmenuoptions(self):
        while True:
            self.menu()
            self.optionspossiblities = [1, 2, 3, 4, 5]
            self.takemenuoption = int(input("Enter Your Option (1/2/3/4/5)\t"))
            try:
                if not self.takemenuoption in self.optionspossiblities:
                    print("Invalid option you entered!!!")
                elif self.takemenuoption == 1:
                    self.add()
                elif self.takemenuoption == 2:
                    self.rm()
                elif self.takemenuoption == 3:
                    self.view()
                elif self.takemenuoption == 4:
                    self.save()
                elif self.takemenuoption == 5:
                    print("Thanks For Comming\nHave a nice day")
                    break
            except Exception as error4:
                print(error4)
    

Setting Up and Running the Script

To run this script, you need to have Python installed on your system. Once Python is installed, you can follow these steps:

  1. Save the script: Save the provided code as a .py file, for example, email_manager.py.
  2. Create a database directory: Ensure that the Projects\database directory exists in the same location as the script, or modify the file paths in the load and save methods accordingly.
  3. Run the script: Open a terminal or command prompt, navigate to the directory where you saved the script, and run it using the command python email_manager.py.

Enhancements and Security Considerations

While this script provides a basic framework for managing email credentials, there are several ways to enhance its functionality and security:

  • Encryption: Storing passwords in plain text is not secure. Implement encryption to protect the stored passwords. Libraries like cryptography or bcrypt can be used for this purpose.
  • User Authentication: Add user authentication to prevent unauthorized access to the email data. This could involve a username and password login.
  • GUI Interface: Develop a graphical user interface (GUI) using libraries like Tkinter or PyQt to make the script more user-friendly.
  • Error Logging: Implement error logging to track and diagnose issues that may occur during script execution.
  • Data Validation: Enhance data validation to ensure that the email and password inputs meet more stringent criteria.

Practical Applications of the Email Manager

This Email Manager script can be used in various scenarios, including:

  • Personal Email Management: Individuals can use it to keep track of their various email accounts and credentials in one place.
  • Small Business: Small businesses can use it to manage email accounts for different departments or employees.
  • Educational Purposes: Students can use it as a learning tool to understand file handling, data persistence, and user input in Python.

Conclusion

The Email Manager script provides a solid foundation for managing email credentials securely. By understanding its core components and functionalities, you can customize and enhance it to meet your specific needs. Remember to prioritize security by implementing encryption and user authentication. This script not only helps in managing emails but also serves as a practical example of how Python can be used to solve real-world problems.

For more information on password security best practices, visit OWASP Password Storage Cheat Sheet.