-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgmail_multi_account.py
More file actions
294 lines (227 loc) · 9.52 KB
/
Copy pathgmail_multi_account.py
File metadata and controls
294 lines (227 loc) · 9.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""
Gmail Multi-Account Manager
Manage multiple Gmail accounts and unified inbox
"""
import os
import json
from gmail_crud import GmailCRUD
class MultiAccountGmail:
"""Manage multiple Gmail accounts with unified operations"""
def __init__(self, config_file='json/accounts_config.json'):
"""
Initialize multi-account manager
Args:
config_file: Path to accounts configuration file
"""
self.config_file = config_file
self.accounts = {}
self.current_account = None
self.load_config()
def load_config(self):
"""Load accounts configuration from file"""
if os.path.exists(self.config_file):
with open(self.config_file, 'r') as f:
config = json.load(f)
self.config = config
# Initialize accounts
for account_name, account_info in config.get('accounts', {}).items():
print(f"Loading account: {account_name} ({account_info.get('email', 'N/A')})")
# Set default account
default = config.get('default_account')
if default and default in config.get('accounts', {}):
self.current_account = default
print(f"✓ Default account: {default}")
else:
print(f"⚠ Config file not found: {self.config_file}")
print("Creating example config...")
self.create_example_config()
def create_example_config(self):
"""Create example configuration file"""
example_config = {
"accounts": {
"personal": {
"email": "your-email@gmail.com",
"credentials_file": "credentials_personal.json",
"token_file": "token_personal.json"
}
},
"default_account": "personal"
}
with open(self.config_file, 'w') as f:
json.dump(example_config, f, indent=2)
print(f"✓ Created example config: {self.config_file}")
print("Please edit this file with your account details")
def save_config(self):
"""Save current configuration to file"""
with open(self.config_file, 'w') as f:
json.dump(self.config, f, indent=2)
def add_account(self, name, email, credentials_file, token_file=None):
"""
Add a new account
Args:
name: Account name (e.g., 'personal', 'work')
email: Gmail address
credentials_file: Path to OAuth credentials JSON
token_file: Path to token file (default: token_{name}.json)
"""
if token_file is None:
token_file = f"token_{name}.json"
if 'accounts' not in self.config:
self.config['accounts'] = {}
self.config['accounts'][name] = {
'email': email,
'credentials_file': credentials_file,
'token_file': token_file
}
self.save_config()
print(f"✓ Added account: {name} ({email})")
# Set as default if first account
if len(self.config['accounts']) == 1:
self.config['default_account'] = name
self.current_account = name
self.save_config()
def remove_account(self, name):
"""Remove an account"""
if name in self.config.get('accounts', {}):
del self.config['accounts'][name]
self.save_config()
print(f"✓ Removed account: {name}")
# Clear current if removed
if self.current_account == name:
self.current_account = None
else:
print(f"✗ Account not found: {name}")
def list_accounts(self):
"""List all configured accounts"""
accounts = self.config.get('accounts', {})
if not accounts:
print("No accounts configured")
return []
print(f"\nConfigured Accounts ({len(accounts)}):")
for name, info in accounts.items():
current = " [CURRENT]" if name == self.current_account else ""
default = " [DEFAULT]" if name == self.config.get('default_account') else ""
print(f" • {name}: {info.get('email', 'N/A')}{current}{default}")
return list(accounts.keys())
def switch_account(self, name):
"""Switch to a different account"""
if name not in self.config.get('accounts', {}):
print(f"✗ Account not found: {name}")
return False
self.current_account = name
print(f"✓ Switched to account: {name}")
return True
def get_account_client(self, account_name=None):
"""
Get GmailCRUD client for specific account
Args:
account_name: Account name (uses current if None)
Returns:
GmailCRUD instance or None
"""
if account_name is None:
account_name = self.current_account
if account_name is None:
print("✗ No account selected")
return None
accounts = self.config.get('accounts', {})
if account_name not in accounts:
print(f"✗ Account not found: {account_name}")
return None
# Get account from cache or create new
if account_name not in self.accounts:
account_info = accounts[account_name]
# Create custom GmailCRUD with account-specific token file
gmail = GmailCRUD(
credentials_file=account_info['credentials_file'],
token_file=account_info['token_file']
)
self.accounts[account_name] = gmail
return self.accounts[account_name]
# ==================== Unified Inbox Operations ====================
def list_all_messages(self, max_results=10, query=''):
"""
List messages from ALL accounts
Args:
max_results: Max messages per account
query: Gmail search query
Returns:
List of dicts with 'account', 'account_email', and message data
"""
all_messages = []
accounts = self.config.get('accounts', {})
print(f"Fetching messages from {len(accounts)} account(s)...")
for account_name, account_info in accounts.items():
print(f"\n📧 {account_name} ({account_info.get('email', 'N/A')})")
gmail = self.get_account_client(account_name)
if gmail:
messages = gmail.list_messages(max_results=max_results, query=query)
# Tag each message with account info
for msg in messages:
msg['_account'] = account_name
msg['_account_email'] = account_info.get('email', 'N/A')
all_messages.extend(messages)
print(f"\n✓ Total messages: {len(all_messages)} from {len(accounts)} account(s)")
return all_messages
def search_all_accounts(self, query, max_results_per_account=50):
"""
Search messages across ALL accounts
Args:
query: Gmail search query
max_results_per_account: Max results per account
Returns:
List of messages from all accounts
"""
all_results = []
accounts = self.config.get('accounts', {})
print(f"Searching '{query}' across {len(accounts)} account(s)...")
for account_name, account_info in accounts.items():
gmail = self.get_account_client(account_name)
if gmail:
messages = gmail.search_messages(query)[:max_results_per_account]
# Tag with account
for msg in messages:
msg['_account'] = account_name
msg['_account_email'] = account_info.get('email', 'N/A')
all_results.extend(messages)
print(f"✓ Found {len(all_results)} total messages")
return all_results
def get_unified_unread_count(self):
"""Get total unread count across all accounts"""
total_unread = 0
accounts = self.config.get('accounts', {})
print("Checking unread across accounts...")
for account_name, account_info in accounts.items():
gmail = self.get_account_client(account_name)
if gmail:
unread = gmail.search_messages('is:unread')
count = len(unread)
total_unread += count
print(f" {account_name}: {count} unread")
print(f"\n✓ Total unread: {total_unread}")
return total_unread
# ==================== Delegate to Current Account ====================
def __getattr__(self, name):
"""
Delegate unknown methods to current account's GmailCRUD
This allows using multi-account manager like regular GmailCRUD:
multi.send_message(...) -> uses current account
"""
gmail = self.get_account_client()
if gmail and hasattr(gmail, name):
return getattr(gmail, name)
raise AttributeError(f"'{type(self).__name__}' has no attribute '{name}'")
if __name__ == '__main__':
print("="*60)
print("Gmail Multi-Account Manager - Demo")
print("="*60)
# Initialize
multi = MultiAccountGmail()
# List accounts
multi.list_accounts()
if multi.current_account:
print(f"\n--- Using account: {multi.current_account} ---")
# Use like regular GmailCRUD
messages = multi.list_messages(max_results=3)
print("\n--- Unified Inbox (All Accounts) ---")
all_messages = multi.list_all_messages(max_results=3)