-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend_mail.py
68 lines (60 loc) · 1.9 KB
/
send_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
import sys
import time
from datetime import datetime
from queue import Empty
import requests
import config
def send_mail(subject, body):
auth = ("api", config.MAILGUN_API_KEY)
data = {"from": config.MAIL_FROM,
"to": [config.MAIL_TO],
"subject": subject,
"text": body}
r = requests.post(
config.MAILGUN_API_URL,
auth=auth,
data=data)
r.raise_for_status()
return r
def empty_queue(queue):
result = []
try:
while True:
result.append(queue.get(block=False))
except Empty:
pass
return result
def mail_daemon(queue):
accumulated_mail = []
last_mail = datetime.min
while True:
try:
msg = queue.get(timeout=1)
accumulated_mail.append(msg)
time.sleep(1)
accumulated_mail.extend(empty_queue(queue))
except Empty:
pass
if not accumulated_mail or (datetime.now() - last_mail).seconds < config.MAIL_RATELIMIT:
continue
if len(accumulated_mail) == 1:
msg = accumulated_mail.pop()
subject = "Received DNS request from {ip}".format(ip=msg['ip'])
body = "{ip} tried to resolve {domain} at {time} server time".format(
ip=msg['ip'],
domain=msg['domain'],
time=msg['time'])
else:
subject = "Received DNS requests"
body = ""
for msg in accumulated_mail:
body += "{ip} tried to resolve {domain} at {time} server time\n".format(
ip=msg['ip'],
domain=msg['domain'],
time=msg['time'])
accumulated_mail = []
try:
send_mail(subject, body)
last_mail = datetime.now()
except Exception as e:
print("Unable to send email: ", e, flush=True, file=sys.stderr)