Automate Your Email Inbox with OpenClaw and Gmail API
In this tutorial, we will walk through the process of automating your email inbox using OpenClaw and the Gmail API. Automation can help you manage your emails effectively, perform bulk operations, and even create custom workflows tailored to your needs.
## Prerequisites
Before we dive into the tutorial, make sure you have the following:
1. **OpenClaw Account**: Sign up for an account on OpenClaw Hub (stormap.ai).
2. **Gmail Account**: You need an active Gmail account to access the Gmail API.
3. **Google Cloud Platform (GCP) Account**: Set up a GCP account to create a project for the Gmail API.
4. **Basic Programming Knowledge**: Familiarity with JSON, REST APIs, and Python (or another programming language of your choice).
5. **OpenClaw SDK**: Install the OpenClaw SDK in your development environment.
## Step-by-Step Instructions
### Step 1: Create a Google Cloud Project
1. Go to the [Google Cloud Console](https://console.cloud.google.com/).
2. Click on the **Select a project** dropdown and then **New Project**.
3. Enter a name for your project (e.g., "Gmail Automation") and click **Create**.
4. Once your project is created, select it from the project dropdown.
### Step 2: Enable the Gmail API
1. In the Cloud Console, navigate to the **API & Services** dashboard.
2. Click on **Enable APIs and Services**.
3. Search for "Gmail API" and select it.
4. Click on the **Enable** button to enable the API for your project.
### Step 3: Create Credentials
1. In the API & Services dashboard, click on **Credentials** in the left sidebar.
2. Click on **Create Credentials** and select **OAuth Client ID**.
3. Configure the consent screen by filling in the required fields (Application name, support email, etc.).
4. For Application type, select **Web application** and fill in the Authorized redirect URIs (e.g., `http://localhost:8080/oauth2callback`).
5. Click **Create**. You will be provided with a **Client ID** and **Client Secret**. Save these for later use.
### Step 4: Set Up OpenClaw with Gmail API
1. Open your terminal and create a new project directory:
```bash
mkdir gmail-automation && cd gmail-automation
```
2. Create a new Python virtual environment (optional but recommended):
```bash
python -m venv venv
source venv/bin/activate
```
3. Install the required libraries:
```bash
pip install requests google-auth google-auth-oauthlib google-auth-httplib2
```
4. Create a file named `gmail_automation.py` and add the following code to set up the Gmail API client:
```python
import os
import requests
import json
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
# If modifying these SCOPES, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
def main():
creds = None
# The file token.json stores the user's access and refresh tokens.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
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 the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
# Call the Gmail API
service = build('gmail', 'v1', credentials=creds)
return service
if __name__ == '__main__':
main()
```
### Step 5: Create a Function to Automate Email Actions
Now let's create a function that will automate actions on your inbox, such as marking emails as read or moving them to a different label.
1. Add the following function to the `gmail_automation.py` file:
```python
def mark_as_read(service, user_id, msg_id):
"""Mark an email as read."""
try:
service.users().messages().modify(
userId=user_id,
id=msg_id,
body={'removeLabelIds': ['UNREAD']}
).execute()
print(f'Marked message {msg_id} as read.')
except Exception as error:
print(f'An error occurred: {error}')
def list_unread_emails(service, user_id):
"""List unread emails."""
try:
results = service.users().messages().list(userId=user_id, labelIds=['INBOX'], q='is:unread').execute()
messages = results.get('messages', [])
if not messages:
print('No unread messages found.')
else:
print('Unread messages:')
for message in messages:
msg_id = message['id']
mark_as_read(service, user_id, msg_id)
except Exception as error:
print(f'An error occurred: {error}')
```
2. Modify the `main()` function to call `list_unread_emails`:
```python
# Call the Gmail API
service = main()
list_unread_emails(service, 'me')
```
### Step 6: Run Your Script
1. Ensure your `credentials.json` file (downloaded from Google Cloud) is in the same directory as `gmail_automation.py`.
2. Run your script using:
```bash
python gmail_automation.py
```
3. Follow the authorization link that appears in your terminal, log in with your Gmail account, and authorize the application.
### Troubleshooting Tips
- **Invalid Credentials Error**: Ensure that your `credentials.json` file is in the correct location and that you have enabled the Gmail API.
- **Permission Denied**: Check if your application has the necessary permissions and scopes.
- **No Unread Emails Found**: Double-check that you have unread emails in your inbox.
## Next Steps
Congratulations! You have successfully set up an automated script using OpenClaw and the Gmail API to manage your email inbox. Here are some related topics you may explore next:
1. **Advanced Email Filtering**: Learn how to filter emails based on various criteria.
2. **Integrating with Other APIs**: Combine the Gmail API with other services for richer automation.
3. **Building a Web Application**: Transform your script into a web app to interact with your emails from anywhere.
With these resources, you can further enhance your email automation skills and create powerful workflows tailored to your needs. Happy coding!