How to import all mail from gmail to csv file

There are a few ways to import all your Gmail emails to a CSV file. Here are a few methods:

Method 1: Using Gmail's built-in export feature

  1. Log in to your Gmail account.
  2. Click on the gear icon in the upper right corner and select "See all settings."
  3. Go to the "Filters and Blocked Addresses" tab.
  4. Click on the "Create a new filter" button.
  5. Enter the following criteria: "has:all" (this will select all emails in your inbox).
  6. Click on the "Create filter" button.
  7. In the "Apply the label" dropdown menu, select "None."
  8. Click on the "Create" button.
  9. A new window will pop up with a link to export your emails. Click on the link.
  10. Choose the CSV format and select the columns you want to export (e.g., From, To, Subject, Body).
  11. Click on the "Export" button.

Method 2: Using a third-party add-on

  1. Install the "Gmail CSV Export" add-on from the Chrome Web Store.
  2. Log in to your Gmail account.
  3. Click on the add-on icon in the upper right corner of the browser.
  4. Select "Export all emails" from the dropdown menu.
  5. Choose the CSV format and select the columns you want to export (e.g., From, To, Subject, Body).
  6. Click on the "Export" button.

Method 3: Using a Python script

  1. Install the imaplib and csv libraries using pip: pip install imaplib csv
  2. Write a Python script to connect to your Gmail account using IMAP and export the emails to a CSV file. Here's an example script:
    
    import imaplib
    import csv

Set up IMAP connection

mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('[email protected]', 'your_password') mail.select('inbox')

Search for all emails

status, messages = mail.search(None, 'ALL')

Loop through each email and extract relevant information

with open('emails.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['From', 'To', 'Subject', 'Body']) # header row for num in messages[0].split(): status, msg = mail.fetch(num, '(RFC822)') raw_message = msg[0][1].decode('utf-8') message = email.message_from_string(raw_message) from_addr = message['From'] to_addr = message['To'] subject = message['Subject'] body = '' for part in message.walk(): if part.get_content_type() == 'text/plain': body = part.get_payload() writer.writerow([from_addr, to_addr, subject, body])

Close IMAP connection

mail.close() mail.logout()


Replace `[email protected]` and `your_password` with your actual Gmail credentials. This script will export all emails in your inbox to a CSV file named `emails.csv`.

Note: Before using any of these methods, make sure you have enabled IMAP access in your Gmail settings.