quota_notify.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/python3
  2. import smtplib
  3. import os
  4. from email.mime.multipart import MIMEMultipart
  5. from email.mime.text import MIMEText
  6. from email.utils import COMMASPACE, formatdate
  7. import jinja2
  8. from jinja2 import Template
  9. import redis
  10. import time
  11. import sys
  12. import html2text
  13. from subprocess import Popen, PIPE, STDOUT
  14. if len(sys.argv) > 2:
  15. percent = int(sys.argv[1])
  16. username = str(sys.argv[2])
  17. else:
  18. print("Args missing")
  19. sys.exit(1)
  20. while True:
  21. try:
  22. r = redis.StrictRedis(host='redis', decode_responses=True, port=6379, db=0)
  23. r.ping()
  24. except Exception as ex:
  25. print('%s - trying again...' % (ex))
  26. time.sleep(3)
  27. else:
  28. break
  29. if r.get('QW_HTML'):
  30. try:
  31. template = Template(r.get('QW_HTML'))
  32. except:
  33. print("Error: Cannot parse quarantine template, falling back to default template.")
  34. with open('/templates/quota.tpl') as file_:
  35. template = Template(file_.read())
  36. else:
  37. with open('/templates/quota.tpl') as file_:
  38. template = Template(file_.read())
  39. html = template.render(username=username, percent=percent)
  40. text = html2text.html2text(html)
  41. try:
  42. msg = MIMEMultipart('alternative')
  43. msg['From'] = r.get('QW_SENDER') or "quota-warning@localhost"
  44. msg['Subject'] = r.get('QW_SUBJ') or "Quota warning"
  45. msg['Date'] = formatdate(localtime = True)
  46. text_part = MIMEText(text, 'plain', 'utf-8')
  47. html_part = MIMEText(html, 'html', 'utf-8')
  48. msg.attach(text_part)
  49. msg.attach(html_part)
  50. msg['To'] = username
  51. p = Popen(['/usr/lib/dovecot/dovecot-lda', '-d', username, '-o', '"plugin/quota=maildir:User quota:noenforcing"'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
  52. p.communicate(input=bytes(msg.as_string(), 'utf-8'))
  53. except Exception as ex:
  54. print('Failed to send quota notification: %s' % (ex))
  55. sys.exit(1)
  56. try:
  57. sys.stdout.close()
  58. except:
  59. pass
  60. try:
  61. sys.stderr.close()
  62. except:
  63. pass