-
Notifications
You must be signed in to change notification settings - Fork 1
/
signal_spam.py
178 lines (139 loc) · 5.18 KB
/
signal_spam.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import os
import time
import json
import email
import base64
import imaplib
import logging
import requests
from email.utils import parsedate_tz, mktime_tz
from logging.handlers import RotatingFileHandler
def process_email(now, email_raw, delay, signal_spam_account):
"""Process the email considered like spam
:param now: timestamp from now
:param email_raw: email content to be processed
:param delay: (optional) ignored all spams below this delay
:param signal_spam_account: Signal Spam account credentials
:return: {@link #send_report}
"""
email_message = email.message_from_bytes(email_raw)
sender = email_message["from"]
date = email_message["date"]
if delay is not None:
tt = parsedate_tz(date)
timestamp = mktime_tz(tt)
if (now - timestamp) < delay:
return False # Ignore this email for the moment
return send_report(signal_spam_account, sender, date, email_raw)
def signal_spam(mailbox):
"""Connects to the email account and process spam
:param mailbox: Mailbox configuration
:return: void
"""
server = mailbox["server"]
host = server["imap"]
port = server["port"]
signal_spam_account = mailbox["signal_spam_account"]
delay = mailbox["delay"]
now = int(time.time())
if server["ssl"]:
box = imaplib.IMAP4_SSL(host, port)
else:
box = imaplib.IMAP4(host, port)
box.login(mailbox["username"], mailbox["password"])
try:
exist, nb_mails = box.select(mailbox["junk"])
nb_mails = nb_mails[0]
if exist == "OK":
if int(nb_mails) > 0:
typ, data = box.search(None, 'ALL')
for num in data[0].split():
typ, data = box.fetch(num, '(RFC822)')
if process_email(now, data[0][1], delay, signal_spam_account):
box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
box.close()
else:
logging.critical(nb_mails)
except imaplib.IMAP4.error as e:
logging.critical(e)
finally:
box.logout()
def send_report(account, sender, date, mail_content):
"""Send a report to Signal Spam
:param account:
:param sender: e-mail of the sender
:param date: date of mail
:param mail_content: content of the email to report
:return: true if the report was sent, else false
"""
url = config["config"]["signal_spam_url"]
timeout = config["config"]["user_agent"]["timeout"]
headers = {
'User-Agent': config["config"]["user_agent"]["agent"],
}
logging.info("Spam report: " + sender + " sent on " + date)
try:
response = requests.post(url=url,
timeout=timeout,
headers=headers,
auth=(account["username"], account["password"]),
data={"message": base64.b64encode(mail_content)}
)
if response.status_code == 200 or response.status_code == 202:
return True
logging.critical("Sending the spam report failed [code: " + str(response.status_code) + "]")
except requests.ConnectionError as e:
logging.critical(e)
except requests.Timeout as e:
logging.critical(e)
return False
def signal_spams():
"""Starts processing for each email account
:return: void
"""
servers = config["servers"]
signal_spam_accounts = config["accounts"]["signal_spam"]
mailbox_accounts = config["accounts"]["mailbox"]
for key, value in mailbox_accounts.items():
if value["enabled"]:
logging.info("Check email account id="+ key)
mailbox = value
mailbox["server"] = servers[mailbox["server"]]
mailbox["signal_spam_account"] = signal_spam_accounts[mailbox["signal_spam_account"]]
try:
signal_spam(mailbox)
except imaplib.IMAP4.error as e:
logging.critical(e)
# Main
if __name__ == '__main__':
current_file = os.path.basename(__file__)
# Logger Settings
logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fileHandler = RotatingFileHandler(current_file + ".log", maxBytes=1000000, backupCount=5) # Max 6 mb of logs
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)
pid = str(os.getpid())
pidfile = "/tmp/" + os.path.splitext(current_file)[0] + ".pid"
if os.path.isfile(pidfile):
logging.critical("Another instance Signal Spam is running !")
exit(0)
f = open(pidfile, 'w')
f.write(pid)
f.close()
try:
config_file_url = "config.json"
with open(config_file_url) as config_file:
config = json.load(config_file)
if config:
logging.info("Configuration loaded, start Signal Spam")
signal_spams()
else:
logging.critical("No configuration loaded")
except IOError as e:
logging.critical(e)
finally:
logging.info("Stop Signal Spam")
os.unlink(pidfile)