quarantine_notify.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. #!/usr/bin/python3
  2. import smtplib
  3. import os
  4. import mysql.connector
  5. from email.mime.multipart import MIMEMultipart
  6. from email.mime.text import MIMEText
  7. from email.utils import COMMASPACE, formatdate
  8. import cgi
  9. import jinja2
  10. from jinja2 import Template
  11. import json
  12. import redis
  13. import time
  14. import html2text
  15. import socket
  16. while True:
  17. try:
  18. r = redis.StrictRedis(host='redis', decode_responses=True, port=6379, db=0)
  19. r.ping()
  20. except Exception as ex:
  21. print('%s - trying again...' % (ex))
  22. time.sleep(3)
  23. else:
  24. break
  25. time_now = int(time.time())
  26. mailcow_hostname = '__MAILCOW_HOSTNAME__'
  27. max_score = float(r.get('Q_MAX_SCORE') or "9999.0")
  28. if max_score == "":
  29. max_score = 9999.0
  30. def query_mysql(query, headers = True, update = False):
  31. while True:
  32. try:
  33. cnx = mysql.connector.connect(unix_socket = '/var/run/mysqld/mysqld.sock', user='__DBUSER__', passwd='__DBPASS__', database='__DBNAME__', charset="utf8")
  34. except Exception as ex:
  35. print('%s - trying again...' % (ex))
  36. time.sleep(3)
  37. else:
  38. break
  39. cur = cnx.cursor()
  40. cur.execute(query)
  41. if not update:
  42. result = []
  43. columns = tuple( [d[0] for d in cur.description] )
  44. for row in cur:
  45. if headers:
  46. result.append(dict(list(zip(columns, row))))
  47. else:
  48. result.append(row)
  49. cur.close()
  50. cnx.close()
  51. return result
  52. else:
  53. cnx.commit()
  54. cur.close()
  55. cnx.close()
  56. def notify_rcpt(rcpt, msg_count, quarantine_acl, category):
  57. if category == "add_header": category = "add header"
  58. meta_query = query_mysql('SELECT SHA2(CONCAT(id, qid), 256) AS qhash, id, subject, score, sender, created, action FROM quarantine WHERE notified = 0 AND rcpt = "%s" AND score < %f AND (action = "%s" OR "all" = "%s")' % (rcpt, max_score, category, category))
  59. print("%s: %d of %d messages qualify for notification" % (rcpt, len(meta_query), msg_count))
  60. if len(meta_query) == 0:
  61. return
  62. msg_count = len(meta_query)
  63. if r.get('Q_HTML'):
  64. try:
  65. template = Template(r.get('Q_HTML'))
  66. except:
  67. print("Error: Cannot parse quarantine template, falling back to default template.")
  68. with open('/templates/quarantine.tpl') as file_:
  69. template = Template(file_.read())
  70. else:
  71. with open('/templates/quarantine.tpl') as file_:
  72. template = Template(file_.read())
  73. html = template.render(meta=meta_query, username=rcpt, counter=msg_count, hostname=mailcow_hostname, quarantine_acl=quarantine_acl)
  74. text = html2text.html2text(html)
  75. count = 0
  76. while count < 15:
  77. count += 1
  78. try:
  79. server = smtplib.SMTP('postfix', 590, 'quarantine')
  80. server.ehlo()
  81. msg = MIMEMultipart('alternative')
  82. msg_from = r.get('Q_SENDER') or "quarantine@localhost"
  83. # Remove non-ascii chars from field
  84. msg['From'] = ''.join([i if ord(i) < 128 else '' for i in msg_from])
  85. msg['Subject'] = r.get('Q_SUBJ') or "Spam Quarantine Notification"
  86. msg['Date'] = formatdate(localtime = True)
  87. text_part = MIMEText(text, 'plain', 'utf-8')
  88. html_part = MIMEText(html, 'html', 'utf-8')
  89. msg.attach(text_part)
  90. msg.attach(html_part)
  91. msg['To'] = str(rcpt)
  92. bcc = r.get('Q_BCC') or ""
  93. redirect = r.get('Q_REDIRECT') or ""
  94. text = msg.as_string()
  95. if bcc == '':
  96. if redirect == '':
  97. server.sendmail(msg['From'], str(rcpt), text)
  98. else:
  99. server.sendmail(msg['From'], str(redirect), text)
  100. else:
  101. if redirect == '':
  102. server.sendmail(msg['From'], [str(rcpt)] + [str(bcc)], text)
  103. else:
  104. server.sendmail(msg['From'], [str(redirect)] + [str(bcc)], text)
  105. server.quit()
  106. for res in meta_query:
  107. query_mysql('UPDATE quarantine SET notified = 1 WHERE id = "%d"' % (res['id']), update = True)
  108. r.hset('Q_LAST_NOTIFIED', record['rcpt'], time_now)
  109. break
  110. except Exception as ex:
  111. server.quit()
  112. print('%s' % (ex))
  113. time.sleep(3)
  114. records = query_mysql('SELECT IFNULL(user_acl.quarantine, 0) AS quarantine_acl, count(id) AS counter, rcpt FROM quarantine LEFT OUTER JOIN user_acl ON user_acl.username = rcpt WHERE notified = 0 AND score < %f AND rcpt in (SELECT username FROM mailbox) GROUP BY rcpt' % (max_score))
  115. for record in records:
  116. attrs = ''
  117. attrs_json = ''
  118. time_trans = {
  119. "hourly": 3600,
  120. "daily": 86400,
  121. "weekly": 604800
  122. }
  123. try:
  124. last_notification = int(r.hget('Q_LAST_NOTIFIED', record['rcpt']))
  125. if last_notification > time_now:
  126. print('Last notification is > time now, assuming never')
  127. last_notification = 0
  128. except Exception as ex:
  129. print('Could not determine last notification for %s, assuming never' % (record['rcpt']))
  130. last_notification = 0
  131. attrs_json = query_mysql('SELECT attributes FROM mailbox WHERE username = "%s"' % (record['rcpt']))
  132. attrs = attrs_json[0]['attributes']
  133. if isinstance(attrs, str):
  134. # if attr is str then just load it
  135. attrs = json.loads(attrs)
  136. else:
  137. # if it's bytes then decode and load it
  138. attrs = json.loads(attrs.decode('utf-8'))
  139. if attrs['quarantine_notification'] not in ('hourly', 'daily', 'weekly'):
  140. continue
  141. if last_notification == 0 or (last_notification + time_trans[attrs['quarantine_notification']]) < time_now:
  142. print("Notifying %s: Considering %d new items in quarantine (policy: %s)" % (record['rcpt'], record['counter'], attrs['quarantine_notification']))
  143. notify_rcpt(record['rcpt'], record['counter'], record['quarantine_acl'], attrs['quarantine_category'])