-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmailsender.py
More file actions
86 lines (67 loc) · 2.58 KB
/
mailsender.py
File metadata and controls
86 lines (67 loc) · 2.58 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
# import json
# import os
# from googleapiclient.discovery import build
# from mailengine.auth import authenticate
# from mailengine.send import send_bulk_emails
# from mailengine.utils import ensure_dir
# CONFIG_FILE = "config/settings.json"
# def load_config(config_path):
# if not os.path.exists(config_path):
# raise FileNotFoundError(f"Configuration file not found at {config_path}")
# with open(config_path, "r", encoding="utf-8") as f:
# return json.load(f)
# def main():
# #---------Load configuration---------
# config = load_config(CONFIG_FILE)
# # ----------Ensure directories exist----------
# for path in [config["log_file"], config["csv_file"], config["template_file"]]:
# ensure_dir(os.path.dirname(path))
# # creds = authenticate(config["scopes"], config["credentials_file"], config["token_file"])
# creds = authenticate()
# service = build("gmail", "v1", credentials=creds)
# # ---------Send emails----------
# send_bulk_emails(service, config)
# if __name__ == "__main__":
# main()
# -------------------new change-------------------
import json
import os
import schedule
import time
from datetime import datetime
from googleapiclient.discovery import build
from mailengine.auth import authenticate
from mailengine.send import send_bulk_emails
from mailengine.utils import ensure_dir
CONFIG_FILE = "config/settings.json"
def load_config(config_path):
if not os.path.exists(config_path):
raise FileNotFoundError(f"Configuration file not found at {config_path}")
with open(config_path, "r", encoding="utf-8") as f:
print(f.read())
f.seek(0)
return json.load(f)
def schedule_email(config):
send_time = config.get("send_time", None)
if send_time:
send_time = datetime.strptime(send_time, "%Y-%m-%d %H:%M:%S")
current_time = datetime.now()
if send_time > current_time:
time_to_wait = (send_time - current_time).total_seconds()
print(f"⏳ Waiting for the scheduled time: {send_time} (Time remaining: {time_to_wait} seconds)")
time.sleep(time_to_wait)
send_email(config)
def send_email(config):
creds = authenticate()
service = build("gmail", "v1", credentials=creds)
for path in [config["log_file"], config["csv_file"], config["template_file"]]:
ensure_dir(os.path.dirname(path))
send_bulk_emails(service, config)
def main():
config = load_config(CONFIG_FILE)
if config.get("send_time"):
schedule_email(config)
else:
send_email(config)
if __name__ == "__main__":
main()