-
Notifications
You must be signed in to change notification settings - Fork 0
/
eprompt.py
162 lines (114 loc) · 4.47 KB
/
eprompt.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
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
#!/usr/bin/env python
import os
import sys
import smtplib
import uuid
import re
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import make_msgid
from imap_tools import MailBox, AND, OR, H
MESSAGE_ID_FILE = f".message_ids"
# could maintain only a single message_id, but presently retains them all for
# bookkeeping
def write_message_id(message_id):
with open(MESSAGE_ID_FILE, "a") as f:
f.write("\n" + message_id)
def read_latest_message_id():
with open(MESSAGE_ID_FILE, "r") as f:
for line in f:
pass
return line.strip()
def smtp_send(message):
mailbox = smtplib.SMTP_SSL(
os.environ["EPROMPT_SMTP_HOST"], os.environ["EPROMPT_SMTP_PORT"]
)
mailbox.ehlo()
mailbox.login(
os.environ["EPROMPT_MAILBOX_USER"], os.environ["EPROMPT_MAILBOX_PASS"]
)
mailbox.sendmail(
os.environ["EPROMPT_MESSAGE_FROM"],
os.environ["EPROMPT_MESSAGE_TO"],
message.as_string(),
)
mailbox.quit()
def compose_and_send_mail():
message = MIMEMultipart()
message["From"] = os.environ["EPROMPT_MESSAGE_FROM"]
message["To"] = os.environ["EPROMPT_MESSAGE_TO"]
message["Subject"] = os.environ["EPROMPT_MESSAGE_SUBJECT"]
message_id = make_msgid(domain=os.environ["EPROMPT_MESSAGE_FROM_DOMAIN"])
message["Message-ID"] = message_id
write_message_id(message_id)
body = os.environ["EPROMPT_MESSAGE_PROMPT"]
message.attach(MIMEText(body))
smtp_send(message)
def delete_mail(mailbox, message_id, response_message_id):
"""Delete the original solicitation message and the entry response."""
mailbox.folder.set(os.environ["EPROMPT_MAILBOX_FOLDER"])
# delete original mail and response
messages_to_delete = mailbox.fetch(
OR(header=[H("Message-ID", message_id), H("Message-ID", response_message_id)])
)
mailbox.delete([m.uid for m in messages_to_delete])
# also delete mail from sent folder
mailbox.folder.set(os.environ["EPROMPT_MAILBOX_SENT_FOLDER"])
messages_to_delete = mailbox.fetch(AND(header=[H("In-Reply-To", message_id)]))
mailbox.delete([m.uid for m in messages_to_delete])
def write_message_to_file(message):
message_year = message.date.year
message_month = str(message.date.month).zfill(2)
message_day = str(message.date.day).zfill(2)
date_filename = f"{message_year}-{message_month}-{message_day}.txt"
with open(f"{os.environ['EPROMPT_OUTPUT_DIR']}/{date_filename}", "a") as f:
formatted_message = format_entry(message)
# print(formatted_message)
f.write(formatted_message)
def read_and_delete_mail():
"""Read the response to the solicitation email, then delete eprompt messages."""
mailbox = MailBox(
os.environ["EPROMPT_IMAP_HOST"], os.environ["EPROMPT_IMAP_PORT"]
).login(os.environ["EPROMPT_MAILBOX_USER"], os.environ["EPROMPT_MAILBOX_PASS"])
mailbox.folder.set(os.environ["EPROMPT_MAILBOX_FOLDER"])
message_id = read_latest_message_id()
response_messages = list(mailbox.fetch(AND(header=[H("In-Reply-To", message_id)])))
if len(response_messages) == 0:
print("no response messages found")
return False
response_message = response_messages[0]
write_message_to_file(response_message)
response_message_id = response_message.headers["message-id"][0]
delete_mail(mailbox, message_id, response_message_id)
return True
HORIZONTAL_LINE_BOLD = (
"================================================================================"
)
HORIZONTAL_LINE = (
"--------------------------------------------------------------------------------"
)
# given a writing entry response email, format it for persistence
def format_entry(msg):
lines = re.sub("\r", "", msg.text).split("\n")
keep_lines = []
for line in lines:
if f"{os.environ['EPROMPT_MESSAGE_FROM']} wrote:" in line:
break
keep_lines.append(line)
keep_lines = [HORIZONTAL_LINE_BOLD, msg.date_str, HORIZONTAL_LINE, ""] + keep_lines
return "\n".join(keep_lines) + "\n"
def print_usage():
print("Usage: python eprompt.py send|read")
if __name__ == "__main__":
if len(sys.argv) < 2:
print_usage()
exit(0)
command = sys.argv[1]
if command == "send":
compose_and_send_mail()
print("Sent writing reminder.")
elif command == "read":
if read_and_delete_mail():
print("Wrote latest entry.")
else:
print_usage()