Skip to content

Commit c41c290

Browse files
Kona Shiny PhoenixKona Shiny Phoenix
authored andcommitted
Update project
0 parents  commit c41c290

17 files changed

Lines changed: 572 additions & 0 deletions

.gitignore

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
env/
12+
build/
13+
develop-eggs/
14+
dist/
15+
downloads/
16+
eggs/
17+
.eggs/
18+
lib/
19+
lib64/
20+
parts/
21+
sdist/
22+
var/
23+
*.egg-info/
24+
.installed.cfg
25+
*.egg
26+
27+
# PyInstaller
28+
# Usually these files are written by a python script from a template
29+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
30+
*.manifest
31+
*.spec
32+
33+
# Installer logs
34+
pip-log.txt
35+
pip-delete-this-directory.txt
36+
37+
# Unit test / coverage reports
38+
htmlcov/
39+
.tox/
40+
.nox/
41+
.coverage
42+
.coverage.*
43+
.cache
44+
nosetests.xml
45+
coverage.xml
46+
*.cover
47+
.hypothesis/
48+
.pytest_cache/
49+
50+
# Jupyter Notebook
51+
.ipynb_checkpoints
52+
53+
# pyenv
54+
.python-version
55+
56+
# mypy
57+
.mypy_cache/
58+
.dmypy.json
59+
60+
# VS Code
61+
.vscode/
62+
63+
# macOS
64+
.DS_Store
65+
66+
# dotenv
67+
.env
68+
.env.*
69+
70+
# Node
71+
node_modules/
72+
package-lock.json
73+
74+
# Other
75+
*.log

CONTRIBUTING.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Contributing to Gmail Automation Python Project
2+
3+
Thank you for your interest in contributing!
4+
5+
## How to Contribute
6+
7+
1. **Fork the repository** and create your branch from `main`.
8+
2. **Clone your fork** and set up the project locally.
9+
3. **Install dependencies**:
10+
```
11+
pip install -r requirements.txt
12+
```
13+
4. **Create a new branch** for your feature or bugfix:
14+
```
15+
git checkout -b my-feature
16+
```
17+
5. **Write clear, PEP8-compliant code** with docstrings and type hints.
18+
6. **Add or update tests** in the `tests/` folder.
19+
7. **Run all tests** before submitting:
20+
```
21+
python -m unittest discover tests
22+
```
23+
8. **Open a pull request** with a clear description of your changes.
24+
25+
## Code Style
26+
- Follow [PEP8](https://www.python.org/dev/peps/pep-0008/) guidelines.
27+
- Use descriptive variable and function names.
28+
- Include docstrings for all public functions and classes.
29+
30+
## Reporting Issues
31+
- Use [GitHub Issues](../../issues) to report bugs or request features.
32+
- Provide as much detail as possible.
33+
34+
## License
35+
By contributing, you agree that your contributions will be licensed under the MIT License.

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2025 Konashinyphoenix
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Gmail Automation Python Project
2+
3+
This project automates Gmail workflows using Python. It fetches emails, applies user-defined rules from `rules.json`, and saves results to PostgreSQL.
4+
5+
## Features
6+
- Gmail API authentication (OAuth2)
7+
- Fetch unread emails
8+
- Parse sender, subject, and snippet
9+
- Apply rules (label, mark as read, etc.) from `rules.json`
10+
- Save results to PostgreSQL
11+
- Unit tests for all major modules
12+
13+
## Project Structure
14+
```
15+
app/
16+
actions.py # Gmail actions (mark as read, label)
17+
auth.py # Gmail API authentication
18+
db.py # PostgreSQL save logic
19+
fetch_emails.py # Fetch and parse emails
20+
main.py # Example orchestrator
21+
rules_engine.py # Rule loading and application
22+
example_gmail_automation.py # Full workflow example
23+
24+
tests/
25+
test_fetch_emails.py
26+
test_rules_engine.py
27+
test_db.py
28+
29+
rules.json # Example rules
30+
requirements.txt # Python dependencies
31+
```
32+
33+
## Setup
34+
1. Install dependencies:
35+
```
36+
pip install -r requirements.txt
37+
```
38+
2. Set up Gmail API credentials:
39+
- Download `credentials.json` from Google Cloud Console.
40+
- Place it in the project root.
41+
3. Set up PostgreSQL and create the `emails` table:
42+
```sql
43+
CREATE TABLE emails (
44+
id TEXT PRIMARY KEY,
45+
from_address TEXT,
46+
subject TEXT,
47+
snippet TEXT,
48+
timestamp TIMESTAMP,
49+
actions JSONB
50+
);
51+
```
52+
4. Edit `rules.json` to define your rules.
53+
54+
## Running
55+
- Run the main workflow:
56+
```
57+
python -m app.main
58+
```
59+
- Or run the full example:
60+
```
61+
python app/example_gmail_automation.py
62+
```
63+
64+
## Testing
65+
Run all tests:
66+
```
67+
python -m unittest discover tests
68+
```
69+
70+
## Example `rules.json`
71+
```
72+
[
73+
{
74+
"criteria": {"from": "newsletter@example.com"},
75+
"actions": ["applyLabel:NEWSLETTERS"]
76+
},
77+
{
78+
"criteria": {"subject": "Invoice"},
79+
"actions": ["markRead"]
80+
}
81+
]
82+
```

app/actions.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from typing import Any
2+
from app.auth import get_gmail_service
3+
4+
def mark_email_as_read(email_id: str) -> None:
5+
"""
6+
Mark an email as read by removing the 'UNREAD' label.
7+
"""
8+
service = get_gmail_service()
9+
service.users().messages().modify(
10+
userId='me',
11+
id=email_id,
12+
body={'removeLabelIds': ['UNREAD']}
13+
).execute()
14+
15+
def apply_label(email_id: str, label_name: str) -> None:
16+
"""
17+
Apply a label to an email. Create the label if it does not exist.
18+
"""
19+
service = get_gmail_service()
20+
labels_res = service.users().labels().list(userId='me').execute()
21+
labels = labels_res.get('labels', [])
22+
label_id = None
23+
for label in labels:
24+
if label['name'] == label_name:
25+
label_id = label['id']
26+
break
27+
if not label_id:
28+
create_res = service.users().labels().create(
29+
userId='me',
30+
body={
31+
'name': label_name,
32+
'labelListVisibility': 'labelShow',
33+
'messageListVisibility': 'show',
34+
}
35+
).execute()
36+
label_id = create_res['id']
37+
service.users().messages().modify(
38+
userId='me',
39+
id=email_id,
40+
body={'addLabelIds': [label_id]}
41+
).execute()

app/auth.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import os
2+
from google.oauth2.credentials import Credentials
3+
from google_auth_oauthlib.flow import InstalledAppFlow
4+
from googleapiclient.discovery import build
5+
from typing import Any
6+
7+
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
8+
9+
def get_gmail_service() -> Any:
10+
"""
11+
Authenticate and return the Gmail API service.
12+
"""
13+
creds = None
14+
if os.path.exists('token.json'):
15+
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
16+
if not creds or not creds.valid:
17+
if creds and creds.expired and creds.refresh_token:
18+
from google.auth.transport.requests import Request
19+
creds.refresh(Request())
20+
else:
21+
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
22+
creds = flow.run_local_server(port=0)
23+
with open('token.json', 'w') as token:
24+
token.write(creds.to_json())
25+
return build('gmail', 'v1', credentials=creds)

app/db.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import os
2+
import psycopg2
3+
from typing import List, Dict, Any
4+
5+
def save_many_emails(emails: List[Dict[str, Any]]) -> None:
6+
"""
7+
Save a list of emails to the PostgreSQL database.
8+
"""
9+
conn = psycopg2.connect(
10+
dbname=os.getenv('DB_NAME', 'gmaildb'),
11+
user=os.getenv('DB_USER', 'postgres'),
12+
password=os.getenv('DB_PASSWORD', 'ksp5779'),
13+
host=os.getenv('DB_HOST', 'localhost'),
14+
port=os.getenv('DB_PORT', '5432')
15+
)
16+
cur = conn.cursor()
17+
for email in emails:
18+
cur.execute(
19+
"""
20+
INSERT INTO emails (id, from_address, subject, snippet, timestamp)
21+
VALUES (%s, %s, %s, %s, to_timestamp(%s / 1000.0))
22+
ON CONFLICT (id) DO NOTHING
23+
""",
24+
(email['id'], email['from'], email['subject'], email['snippet'], email['timestamp'])
25+
)
26+
conn.commit()
27+
cur.close()
28+
conn.close()

0 commit comments

Comments
 (0)