]> TLD Linux GIT Repositories - tld-builder.git/blob - TLD_Builder/mailer.py
- fixed mail encoding errors
[tld-builder.git] / TLD_Builder / mailer.py
1 # vi: encoding=utf-8 ts=8 sts=4 sw=4 et
2
3 import time
4 import os
5 import sys
6 from io import StringIO
7 from config import config
8 import shutil
9 import log
10 import util
11
12 class Message:
13     def __init__(self):
14         self.headers = {}
15         self.body = StringIO()
16         self.set_std_headers()
17
18     def set_header(self, n, v):
19         self.headers[n] = v
20
21     def set_headers(self, to = None, cc = None, subject = None):
22         if to != None:
23             self.set_header("To", to)
24         if cc != None:
25             self.set_header("Cc", cc)
26         if subject != None:
27             self.set_header("Subject", subject)
28
29     def remove_header(self, n):
30         if n in self.headers:
31             del self.headers[n]
32
33     def write_line(self, l):
34         self.body.write(util.to_str("%s\n" % l))
35
36     def write(self, s):
37         self.body.write(util.to_str(s))
38
39     def append_log(self, log):
40         s = os.stat(log)
41         if s.st_size > 50000:
42             # just head and tail
43             f = open(log)
44             line_cnt = 0
45             for l in f:
46                 line_cnt += 1
47             f.seek(0)
48             line = 0
49             for l in f:
50                 if line < 100 or line > line_cnt - 100:
51                     self.body.write(util.to_str(l))
52                 if line == line_cnt - 100:
53                     self.body.write("\n\n[...]\n\n")
54                 line += 1
55         else:
56             shutil.copyfileobj(open(log), self.body)
57
58     def set_std_headers(self):
59         self.headers["Date"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
60         self.headers["Message-ID"] = "<tld-builder.%f.%d@%s>" \
61                 % (time.time(), os.getpid(), os.uname()[1])
62         self.headers["From"] = "TLD %s builder <%s>" \
63                 % (config.builder, config.email)
64         self.headers["X-TLD-Builder"] = config.builder
65
66     def write_to(self, f):
67         for k, v in self.headers.items():
68             f.write("%s: %s\n" % (k, v))
69         f.write("\n")
70         self.body.seek(0)
71         shutil.copyfileobj(self.body, f)
72
73     def send(self):
74         if not os.path.exists("/usr/lib/sendmail"):
75             # TODO: dump to file?
76             log.alert("/usr/lib/sendmail doesn't exist: Can't send email")
77             return False
78         send_sendmail = "/usr/lib/sendmail -i -t -f %s" % config.admin_email
79         f = os.popen(send_sendmail, "w")
80         try:
81             self.write_to(f)
82         except IOError as e:
83             log.alert("sending email message failed: %s" % e)
84             f.close()
85             return False
86         return f.close()