Gmail_Contact_Extractor
Build a Python Gmail Contact Extractor with a GUI
Gmail_Contact_Extractor
Out of respect for data privacy I used a screenshot that only listed the LinkedIn emails found however it was able to extract an email for every single sender I have ever received a message from.

 

Welcome to PrometheanLink! In this comprehensive guide, we’ll walk you through building a Python application that connects to your Gmail account, reads all messages, and extracts names and email addresses. We’ll enhance this application with a user-friendly graphical interface (GUI) using Tkinter, making it accessible even if you’re not deeply familiar with command-line operations.

1. Prerequisites

Before we begin, ensure you have the following:

  • Python 3.6 or higher: Download and install from python.org.
  • A Google Account: You’ll need access to Gmail.
  • Basic Knowledge of Python: Familiarity with Python scripting will be beneficial.</

2. Setting Up the Google API

To interact with Gmail programmatically, we need to set up a project in the Google Cloud Console and obtain the necessary credentials. Follow these steps:

Step 1: Create a Google Cloud Project

  1. Go to the Google Cloud Console.
  2. Click on the project dropdown at the top and select “New Project”.
  3. Enter a project name, e.g., “GmailContactExtractor”, and click “Create”.

Step 2: Enable the Gmail API

  1. Within your newly created project, navigate to APIs & Services > Library in the sidebar.
  2. Search for “Gmail API” and select it from the search results.
  3. Click the “Enable” button to activate the API for your project.

Step 3: Configure OAuth Consent Screen

  1. Go to APIs & Services > OAuth consent screen in the sidebar.
  2. Select “External” as the user type and click “Create”.
  3. Fill in the required details:
    • App name: e.g., “Gmail Contact Extractor”
    • User support email: Your email address.
    • Developer contact information: Your email address.
  4. Click “Save and Continue” through the scopes and test users sections, accepting defaults.

Step 4: Create OAuth 2.0 Credentials

  1. Navigate to APIs & Services > Credentials.
  2. Click on “Create Credentials” and select “OAuth client ID”.
  3. Select “Desktop app” as the application type and provide a name, e.g., “GmailContactExtractorApp”.
  4. Click “Create”.
  5. After creation, click “OK” and then download the credentials.json file by clicking the download icon next to your newly created credentials.
  6. Save the credentials.json file in your project directory. Keep this file secure!

3. Installing Required Python Libraries

We’ll need several Python libraries to build and run our application. Open your terminal or command prompt and execute the following commands:

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Note: If you’re using Python 3 and encounter issues, you might need to use pip3 instead of pip.

4. Building the GUI Application

We’ll use Tkinter, Python’s standard GUI library, to create a user-friendly interface. The application will allow users to authenticate with Gmail, scan emails, extract contacts, display them, and export the results to a CSV file.

Complete Python Script

Below is the complete Python script for the GUI-based Gmail Contact Extractor:


import os
import base64
import re
import csv
import threading
from email import message_from_bytes
from email.utils import parseaddr
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# Define the scopes
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
class GmailContactExtractorApp:
    def __init__(self, master):
        self.master = master
        self.master.title("Gmail Contact Extractor")
        self.master.geometry("800x600")
        self.contacts = set()
        # Create GUI components
        self.create_widgets()
    def create_widgets(self):
        # Frame for buttons
        button_frame = tk.Frame(self.master)
        button_frame.pack(pady=10)
        # Login Button
        self.login_button = tk.Button(button_frame, text="Login with Gmail", command=self.authenticate_gmail)
        self.login_button.pack(side=tk.LEFT, padx=10)
        # Export Button
        self.export_button = tk.Button(button_frame, text="Export to CSV", command=self.export_contacts, state=tk.DISABLED)
        self.export_button.pack(side=tk.LEFT, padx=10)
        # Progress Bar
        self.progress = ttk.Progressbar(self.master, orient='horizontal', mode='determinate', length=700)
        self.progress.pack(pady=10)
        # Status Label
        self.status_label = tk.Label(self.master, text="Status: Not authenticated.")
        self.status_label.pack()
        # Treeview for displaying contacts
        columns = ("Name", "Email Address")
        self.tree = ttk.Treeview(self.master, columns=columns, show='headings')
        self.tree.heading("Name", text="Name")
        self.tree.heading("Email Address", text="Email Address")
        self.tree.column("Name", width=200)
        self.tree.column("Email Address", width=400)
        self.tree.pack(pady=10, fill=tk.BOTH, expand=True)
        # Add scrollbar
        scrollbar = ttk.Scrollbar(self.tree, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscroll=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    def authenticate_gmail(self):
        """Authenticate the user and start the contact extraction process."""
        self.login_button.config(state=tk.DISABLED)
        self.status_label.config(text="Status: Authenticating...")
        threading.Thread(target=self._authenticate_and_extract).start()
    def _authenticate_and_extract(self):
        """Handles authentication and extraction in a separate thread."""
        creds = None
        try:
            # Check if token.json exists
            if os.path.exists('token.json'):
                creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            # If no valid credentials, initiate login
            if not creds or not creds.valid:
                if creds and creds.expired and creds.refresh_token:
                    creds.refresh(Request())
                else:
                    flow = InstalledAppFlow.from_client_secrets_file(
                        'credentials.json', SCOPES)
                    creds = flow.run_local_server(port=0)
                # Save the credentials for future use
                with open('token.json', 'w') as token:
                    token.write(creds.to_json())
            # Build the Gmail service
            service = build('gmail', 'v1', credentials=creds)
            self.status_label.config(text="Status: Fetching messages...")
            messages = self.get_all_messages(service)
            total_messages = len(messages)
            self.progress.config(maximum=total_messages)
            self.status_label.config(text=f"Status: Processing {total_messages} messages...")
            for idx, msg in enumerate(messages, start=1):
                mime_msg = self.get_message(service, msg['id'])
                if mime_msg:
                    contacts = self.extract_contacts(mime_msg)
                    self.contacts.update(contacts)
                # Update progress bar
                self.progress['value'] = idx
                self.master.update_idletasks()
            self.status_label.config(text=f"Status: Extraction complete. {len(self.contacts)} contacts found.")
            self.populate_treeview()
            self.export_button.config(state=tk.NORMAL)
        except Exception as e:
            messagebox.showerror("Error", f"An error occurred: {e}")
            self.status_label.config(text="Status: Error occurred.")
            self.login_button.config(state=tk.NORMAL)
    def get_all_messages(self, service, user_id='me'):
        """Retrieve all messages from the user's mailbox."""
        messages = []
        try:
            response = service.users().messages().list(userId=user_id, maxResults=500).execute()
            if 'messages' in response:
                messages.extend(response['messages'])
            # Handle pagination
            while 'nextPageToken' in response:
                page_token = response['nextPageToken']
                response = service.users().messages().list(userId=user_id, pageToken=page_token, maxResults=500).execute()
                if 'messages' in response:
                    messages.extend(response['messages'])
        except Exception as error:
            print(f'An error occurred while fetching messages: {error}')
        return messages
    def get_message(self, service, msg_id, user_id='me'):
        """Retrieve a full message by ID."""
        try:
            message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
            msg_raw = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
            mime_msg = message_from_bytes(msg_raw)
            return mime_msg
        except Exception as error:
            print(f'An error occurred while fetching message {msg_id}: {error}')
            return None
    def extract_contacts(self, mime_msg):
        """Extract names and email addresses from a MIME message."""
        contacts = set()
        headers = ['From', 'To', 'Cc', 'Bcc']
        for header in headers:
            header_value = mime_msg.get(header)
            if header_value:
                # Split multiple addresses
                addresses = header_value.split(',')
                for addr in addresses:
                    name, email = parseaddr(addr)
                    email = email.lower()
                    if email:
                        contacts.add((name.strip(), email))
        # Optionally, extract from the email body
        if mime_msg.is_multipart():
            for part in mime_msg.walk():
                if part.get_content_type() == 'text/plain':
                    try:
                        body = part.get_payload(decode=True).decode('utf-8', errors='ignore')
                        contacts.update(self.extract_contacts_from_text(body))
                    except Exception as e:
                        print(f'Error decoding part of the message: {e}')
        else:
            try:
                body = mime_msg.get_payload(decode=True).decode('utf-8', errors='ignore')
                contacts.update(self.extract_contacts_from_text(body))
            except Exception as e:
                print(f'Error decoding message body: {e}')
        return contacts
    def extract_contacts_from_text(self, text):
        """Extract email addresses and attempt to find associated names in the text."""
        contacts = set()
        # Simple regex to find email addresses
        email_regex = r'[\w\.-]+@[\w\.-]+\.\w+'
        emails = re.findall(email_regex, text)
        for email in emails:
            contacts.add(('', email.lower()))  # Names may not be present in the body
        return contacts
    def populate_treeview(self):
        """Populate the Treeview with extracted contacts."""
        # Clear existing data
        for item in self.tree.get_children():
            self.tree.delete(item)
        # Insert new data
        for name, email in sorted(self.contacts, key=lambda x: x[1]):
            self.tree.insert('', tk.END, values=(name, email))
    def export_contacts(self):
        """Export the contacts to a CSV file."""
        if not self.contacts:
            messagebox.showwarning("No Contacts", "There are no contacts to export.")
            return
        # Ask user where to save the CSV
        file_path = filedialog.asksaveasfilename(defaultextension='.csv',
                                                 filetypes=[('CSV files', '*.csv')],
                                                 title="Save Contacts As")
        if file_path:
            try:
                with open(file_path, mode='w', newline='', encoding='utf-8') as csvfile:
                    contact_writer = csv.writer(csvfile)
                    contact_writer.writerow(['Name', 'Email Address'])
                    for name, email in sorted(self.contacts, key=lambda x: x[1]):
                        contact_writer.writerow([name, email])
                messagebox.showinfo("Success", f"Contacts have been exported to {file_path}")
            except Exception as e:
                messagebox.showerror("Error", f"Failed to export contacts: {e}")
def main():
    root = tk.Tk()
    app = GmailContactExtractorApp(root)
    root.mainloop()
if __name__ == '__main__':
    main()
        

Understanding the Script

Let’s break down the main components of the application:

Imports

We import necessary modules for handling emails, regular expressions, threading, GUI components, and interacting with Google’s API.

Here is the library in case your IDE doesn’t automatically locate it. https://pypi.org/project/google-api-python-client/#files

SCOPES

Defines the permissions the application is requesting. In this case, read-only access to Gmail.

GmailContactExtractorApp Class

This class encapsulates all functionalities of the application, including GUI creation, authentication, email processing, contact extraction, and exporting.

  • __init__: Initializes the GUI components and sets up the application window.
  • create_widgets: Constructs the GUI elements, including buttons, progress bar, status label, and the Treeview for displaying contacts.
  • authenticate_gmail: Triggered when the user clicks the “Login with Gmail” button. Disables the button and starts a new thread for authentication and extraction.
  • _authenticate_and_extract: Handles the authentication flow and contact extraction in a separate thread to keep the GUI responsive.
  • get_all_messages: Fetches all email messages from the user’s Gmail account, handling pagination.
  • get_message: Retrieves the raw content of a specific email message and parses it into a MIME message.
  • extract_contacts: Extracts names and email addresses from email headers and optionally from the email body.
  • extract_contacts_from_text: Uses a regex to find email addresses within a block of text.
  • populate_treeview: Displays the extracted contacts in the Treeview widget.
  • export_contacts: Allows users to export the displayed contacts to a CSV file using a file dialog.

Main Function

Initializes the Tkinter root window and starts the application.

def main():
    root = tk.Tk()
    app = GmailContactExtractorApp(root)
    root.mainloop()
if __name__ == '__main__':
    main()

5. Running the Application

Follow these steps to run your newly created Gmail Contact Extractor:

Step 1: Ensure Credentials Are in Place

Make sure the downloaded credentials.json file is in the same directory as your Python script.

Step 2: Execute the Script

  1. Open your terminal or command prompt.
  2. Navigate to your project directory using the cd command.
  3. Run the script with the following command:
python gmail_contact_extractor.py

Step 3: Authenticate with Gmail

  1. Click the “Login with Gmail” button in the application window.
  2. A browser window will open prompting you to sign in to your Google account and grant the requested permissions.
  3. After successful authentication, the application will begin scanning your emails.

Step 4: Monitor Progress

The progress bar will indicate the scanning progress, and the status label will provide real-time updates.

Step 5: View Extracted Contacts

Once scanning is complete, the extracted names and email addresses will populate the table in the GUI.

Step 6: Export Contacts

  1. Click the “Export to CSV” button.
  2. Select a destination and filename for the CSV file.
  3. The contacts will be saved accordingly.

Note: The initial run might take some time, especially if you have a large number of emails. Subsequent runs will be faster due to cached credentials.

6. Enhancements and Best Practices

While the provided application is functional, consider the following enhancements and best practices for a more robust and user-friendly experience:

Asynchronous Operations

Current Implementation: Uses threading to prevent the GUI from freezing during long operations.

Enhancement: Implement more sophisticated asynchronous handling, possibly using asyncio, for better performance.

Error Handling

Current Implementation: Basic error handling with message boxes.

Enhancement: Implement logging to a file for debugging purposes and provide more detailed error messages.

User Feedback

Enhancement: Display the number of contacts found dynamically or show contacts being added in real-time.

Filtering and Search

Enhancement: Add search functionality within the Treeview to allow users to find specific contacts quickly.

Pagination in Treeview

Enhancement: For very large contact lists, implement pagination or virtual scrolling to improve performance.

Advanced Export Options

Enhancement: Allow exporting in different formats such as Excel (.xlsx) or JSON.

Improved UI Design

Enhancement: Use advanced GUI frameworks like PyQt or Kivy for a more modern and feature-rich interface.

Incremental Scanning

Enhancement: Implement functionality to scan only new or unread emails in subsequent runs to save time.

Data Privacy

Best Practice: Inform users about how their data is handled and ensure compliance with privacy regulations.

Unit Testing

Best Practice: Write unit tests for critical functions to ensure reliability.

7. Conclusion

Congratulations! You’ve successfully built a Python application that connects to your Gmail account, scans your emails, extracts names and email addresses, and presents them in a user-friendly GUI. This tool can serve as a foundation for more advanced applications, such as contact management systems, data analysis tools, or personalized communication platforms.

Remember:

  • Keep your credentials.json and token.json files secure. Do not share them or commit them to public repositories.
  • Handle extracted data responsibly to maintain privacy and adhere to best practices.
  • Explore further enhancements to tailor the application to your specific needs.

If you encounter any issues or have further questions, feel free to reach out or explore more resources on our website.

Happy coding!