Reputation: 19
I'm currently trying to get all emails of users of my google workspace (i have an admin account)!
i started by doing these steps on the console.
Create a project in Google Cloud Platform (GCP) Console.
Activate the Gmail API for your project by going to "APIs & Services" -> "Library", search for "Gmail" and activate the API.
Create API access credentials. To do this, go to "APIs & Services" -> "Credentials", then click on "Create Credentials" and select "Service account". Follow the steps to create the service account.
Once the service account has been created, you'll be presented with a JSON file containing your keys. Keep this file safe. You'll use it in your application to authenticate to the API.
Configure domain delegation for your service account. To do this, go to "IAM & Admin" -> "Service accounts", click on the service account you've created, then click on "Add Key" and select "JSON". Download the JSON file.
Go to your Google Workspace admin console at admin.google.com. Click on "Security" -> "API controls", then in the "Domain-wide delegation" section, click on "Manage Domain-Wide Delegation". Click on "Add new", then enter the client ID of the service account (which you can find in the JSON file you downloaded in step 5) and enter the scopes you want to delegate (for example, "https://www.googleapis.com/auth/gmail.readonly"). Click on "Authorize".
then i added this code
from gmail_connector.mixins.email_scraper import Extract
from gmail_connector.mixins.check import Check
from gmail_connector.logging import Logger
from googleapiclient.discovery import build
from google.oauth2 import service_account
import json
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
SUBJECT = 'me'
with open("C:/Python310/mailchecking01-d253ce85770d.json") as f:
service_account_info = json.load(f)
print(service_account_info)
# Création des credentials
creds = service_account.Credentials.from_service_account_file("C:/Python310/mailchecking01-d253ce85770d.json", scopes=SCOPES)
print(creds)
# Construction du service
service = build('gmail', 'v1', credentials=creds)
try:
results = service.users().messages().list(userId='me').execute()
print('Retrieved email list successfully. The list is:')
print(results)
except Exception as e:
print('Failed to retrieve email list. The error message is:')
print(e)
this code gives me my credentials ! but he also shows me : Failed to retrieve email list. The error message is:
<HttpError 403 when requesting https://gmail.googleapis.com/gmail/v1/users/me/profile?alt=json
Upvotes: 1
Views: 1740
Reputation: 541
I used this code (courtesy of ChatGPT), which worked. It lists the latest 10 mails of the given mail address.
from google.oauth2 import service_account
from googleapiclient.discovery import build
import base64
import email
# Configuration
SERVICE_ACCOUNT_FILE = 'xyz.json'
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
USER_EMAIL = '[email protected]' # Email of the user you want to impersonate
def get_gmail_service():
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject(USER_EMAIL)
service = build('gmail', 'v1', credentials=delegated_credentials)
return service
def list_messages(service, user_id):
# List the first 10 messages
results = service.users().messages().list(userId=user_id, maxResults=10).execute()
return results.get('messages', [])
def get_message(service, user_id, msg_id):
# Get a specific message
message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
mime_msg = email.message_from_bytes(msg_str)
return mime_msg
def main():
service = get_gmail_service()
messages = list_messages(service, USER_EMAIL)
for message in messages:
msg = get_message(service, USER_EMAIL, message['id'])
print(f"Subject: {msg['subject']}")
print(f"From: {msg['from']}")
print("")
if __name__ == '__main__':
main()
Upvotes: 1
Reputation: 117254
You need to delegate to a user on your domain
credentials = ServiceAccountCredentials.from_json_keyfile_name(
SERVICE_ACCOUNT_FILE_PATH,
scopes=SCOPES)
credentials = credentials.create_delegated(user_email)
Upvotes: 0