quota_notify.py 1.9 KB

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