-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread_mail.py
79 lines (67 loc) · 2.51 KB
/
read_mail.py
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
import itertools
import json
import os.path
import pickle
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from tqdm import tqdm
SCOPES = ['https://mail.google.com/']
class Gmail:
def __init__(self, username, senders):
self.username = username
self.api = self.get_api()
self.senders = senders
def get_api(self):
creds = None
token_name = f"token/{self.username}.pickle"
if os.path.exists(token_name):
with open(token_name, 'rb') as token:
creds = pickle.load(token)
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/credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
if not os.path.exists('token'):
os.mkdir("token")
with open(token_name, 'wb') as token:
pickle.dump(creds, token)
api = build('gmail', 'v1', credentials=creds)
return api
def get_mails_with_sender_address(self, sender_address):
api = self.api.users().messages()
filtered_messages = api.list(
userId='me',
labelIds=["UNREAD"],
q=f'from:{sender_address}').execute()
if filtered_messages["resultSizeEstimate"] == 0:
return
return filtered_messages["messages"]
def read_mail(self, message):
response = self.api.users().messages().modify(
userId="me",
id=message["id"],
body={"addLabelIds": [], "removeLabelIds": ["UNREAD"]}
).execute()
return
def main(username_list, senders_list):
for username, senders in zip(username_list, senders_list):
client = Gmail(username, senders)
read_mails = [
messages for s in senders
if (messages := client.get_mails_with_sender_address(s))]
read_mails = list(itertools.chain.from_iterable(read_mails))
if (mails_count := len(read_mails)) == 0:
continue
print(f"{username}: 自動既読するメール{mails_count}件")
[client.read_mail(x) for x in tqdm(read_mails)]
if __name__ == '__main__':
with open("data.json") as f:
user_data = json.load(f)
main(
user_data.keys(),
user_data.values()
)