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