##// END OF EJS Templates
Skip email notification if email or server are empty
Miguel Valdez -
r733:f32e8d5e77bd
parent child
Show More
@@ -1,382 +1,388
1 1 """The admin module contains all administrative classes relating to the schain python api.
2 2
3 3 The main role of this module is to send some reports. It contains a
4 4 notification class and a standard error handing class.
5 5
6 6 $Id: admin.py 3966 2015-12-01 14:32:29Z miguel.urco $
7 7 """
8 8 import os, sys
9 9 import traceback
10 10 import smtplib
11 11 import ConfigParser
12 12 import StringIO
13 13
14 14 from email.mime.text import MIMEText
15 15 from email.mime.application import MIMEApplication
16 16 from email.mime.multipart import MIMEMultipart
17 17
18 18 class SchainConfigure():
19 19
20 20 __DEFAULT_ADMINISTRATOR_EMAIL = "miguel.urco@jro.igp.gob.pe"
21 21 __DEFAULT_EMAIL_SERVER = "jro-zimbra.igp.gob.pe"
22 22 __DEFAULT_SENDER_EMAIL = "notifier-schain@jro.igp.gob.pe"
23 23 __DEFAULT_SENDER_PASS = ""
24 24
25 25 __SCHAIN_ADMINISTRATOR_EMAIL = "CONTACT"
26 26 __SCHAIN_EMAIL_SERVER = "MAILSERVER"
27 27 __SCHAIN_SENDER_EMAIL = "MAILSERVER_ACCOUNT"
28 28 __SCHAIN_SENDER_PASS = "MAILSERVER_PASSWORD"
29 29
30 30 def __init__(self, initFile = None):
31 31
32 32 # Set configuration file
33 33 if (initFile == None):
34 34 self.__confFilePath = "/etc/schain.conf"
35 35 else:
36 36 self.__confFilePath = initFile
37 37
38 38 # open configuration file
39 39 try:
40 40 self.__confFile = open(self.__confFilePath, "r")
41 41 except IOError:
42 42 # can't read from file - use all hard-coded values
43 43 self.__initFromHardCode()
44 44 return
45 45
46 46 # create Parser using standard module ConfigParser
47 47 self.__parser = ConfigParser.ConfigParser()
48 48
49 49 # read conf file into a StringIO with "[madrigal]\n" section heading prepended
50 50 strConfFile = StringIO.StringIO("[schain]\n" + self.__confFile.read())
51 51
52 52 # parse StringIO configuration file
53 53 self.__parser.readfp(strConfFile)
54 54
55 55 # read information from configuration file
56 56 self.__readConfFile()
57 57
58 58 # close conf file
59 59 self.__confFile.close()
60 60
61 61
62 62 def __initFromHardCode(self):
63 63
64 64 self.__sender_email = self.__DEFAULT_SENDER_EMAIL
65 65 self.__sender_pass = self.__DEFAULT_SENDER_PASS
66 66 self.__admin_email = self.__DEFAULT_ADMINISTRATOR_EMAIL
67 67 self.__email_server = self.__DEFAULT_EMAIL_SERVER
68 68
69 69 def __readConfFile(self):
70 70 """__readConfFile is a private helper function that reads information from the parsed config file.
71 71
72 72 Inputs: None
73 73
74 74 Returns: Void.
75 75
76 76 Affects: Initializes class member variables that are found in the config file.
77 77
78 78 Exceptions: MadrigalError thrown if any key not found.
79 79 """
80 80
81 81 # get the sender email
82 82 try:
83 83 self.__sender_email = self.__parser.get("schain", self.__SCHAIN_SENDER_EMAIL)
84 84 except:
85 85 self.__sender_email = self.__DEFAULT_SENDER_EMAIL
86 86
87 87 # get the sender password
88 88 try:
89 89 self.__sender_pass = self.__parser.get("schain", self.__SCHAIN_SENDER_PASS)
90 90 except:
91 91 self.__sender_pass = self.__DEFAULT_SENDER_PASS
92 92
93 93 # get the administrator email
94 94 try:
95 95 self.__admin_email = self.__parser.get("schain", self.__SCHAIN_ADMINISTRATOR_EMAIL)
96 96 except:
97 97 self.__admin_email = self.__DEFAULT_ADMINISTRATOR_EMAIL
98 98
99 99 # get the server email
100 100 try:
101 101 self.__email_server = self.__parser.get("schain", self.__SCHAIN_EMAIL_SERVER)
102 102 except:
103 103 self.__email_server = self.__DEFAULT_EMAIL_SERVER
104 104
105 105 def getEmailServer(self):
106 106
107 107 return self.__email_server
108 108
109 109 def getSenderEmail(self):
110 110
111 111 return self.__sender_email
112 112
113 113 def getSenderPass(self):
114 114
115 115 return self.__sender_pass
116 116
117 117 def getAdminEmail(self):
118 118
119 119 return self.__admin_email
120 120
121 121 class SchainNotify:
122 122 """SchainNotify is an object used to send messages to an administrator about a Schain software.
123 123
124 124 This object provides functions needed to send messages to an administrator about a Schain , for now
125 125 only sendAlert, which sends an email to the site administrator found is ADMIN_EMAIL
126 126
127 127 Usage example:
128 128
129 129 import schainpy.admin
130 130
131 131 try:
132 132
133 133 adminObj = schainpy.admin.SchainNotify()
134 134 adminObj.sendAlert('This is important!', 'Important Message')
135 135
136 136 except schainpy.admin.SchainError, e:
137 137
138 138 print e.getExceptionStr()
139 139
140 140
141 141 Non-standard Python modules used:
142 142 None
143 143
144 144 Exceptions thrown: None - Note that SchainNotify tries every trick it knows to avoid
145 145 throwing exceptions, since this is the class that will generally be called when there is a problem.
146 146
147 147 Change history:
148 148
149 149 Written by "Miguel Urco":mailto:miguel.urco@jro.igp.gob.pe Dec. 1, 2015
150 150 """
151 151
152 152 #constants
153 153
154 154 def __init__(self):
155 155 """__init__ initializes SchainNotify by getting some basic information from SchainDB and SchainSite.
156 156
157 157 Note that SchainNotify tries every trick it knows to avoid throwing exceptions, since
158 158 this is the class that will generally be called when there is a problem.
159 159
160 160 Inputs: Existing SchainDB object, by default = None.
161 161
162 162 Returns: void
163 163
164 164 Affects: Initializes self.__binDir.
165 165
166 166 Exceptions: None.
167 167 """
168 168
169 169 # note that the main configuration file is unavailable
170 170 # the best that can be done is send an email to root using localhost mailserver
171 171 confObj = SchainConfigure()
172 172
173 173 self.__emailFromAddress = confObj.getSenderEmail()
174 174 self.__emailPass = confObj.getSenderPass()
175 175 self.__emailToAddress = confObj.getAdminEmail()
176 176 self.__emailServer = confObj.getEmailServer()
177 177
178 178 def sendEmail(self, email_from, email_to, subject='Error running ...', message="", subtitle="", filename="", html_format=True):
179 179
180 if not email_to:
181 return 0
182
183 if not self.__emailServer:
184 return 0
185
180 186 msg = MIMEMultipart()
181 187 msg['Subject'] = subject
182 188 msg['From'] = "(Python SChain API): " + email_from
183 189 msg['Reply-to'] = email_from
184 190 msg['To'] = email_to
185 191
186 192 # That is what u see if dont have an email reader:
187 193 msg.preamble = 'SChainPy'
188 194
189 195 if html_format:
190 196 message = "<h1> %s </h1>" %subject + "<h3>" + subtitle.replace("\n", "</h3><h3>\n") + "</h3>" + message.replace("\n", "<br>\n")
191 197 message = "<html>\n" + message + '</html>'
192 198
193 199 # This is the textual part:
194 200 part = MIMEText(message, "html")
195 201 else:
196 202 message = subject + "\n" + subtitle + "\n" + message
197 203 part = MIMEText(message)
198 204
199 205 msg.attach(part)
200 206
201 207 if os.path.isfile(filename):
202 208 # This is the binary part(The Attachment):
203 209 part = MIMEApplication(open(filename,"rb").read())
204 210 part.add_header('Content-Disposition',
205 211 'attachment',
206 212 filename=os.path.basename(filename))
207 213 msg.attach(part)
208 214
209 215 # Create an instance in SMTP server
210 216 try:
211 217 smtp = smtplib.SMTP(self.__emailServer)
212 218 except:
213 219 print "***** Could not connect to server %s *****" %self.__emailServer
214 220 return 0
215 221
216 222 # Start the server:
217 223 # smtp.ehlo()
218 224 if self.__emailPass:
219 225 smtp.login(self.__emailFromAddress, self.__emailPass)
220 226
221 227 # Send the email
222 228 try:
223 229 smtp.sendmail(msg['From'], msg['To'], msg.as_string())
224 230 except:
225 231 print "***** Could not send the email to %s *****" %msg['To']
226 232 smtp.quit()
227 233 return 0
228 234
229 235 smtp.quit()
230 236
231 237 return 1
232 238
233 239 def sendAlert(self, message, subject = "", subtitle="", filename=""):
234 240 """sendAlert sends an email with the given message and optional title.
235 241
236 242 Inputs: message (string), and optional title (string)
237 243
238 244 Returns: void
239 245
240 246 Affects: none
241 247
242 248 Exceptions: None.
243 249 """
244 250 print "***** Sending alert to %s *****" %self.__emailToAddress
245 251 # set up message
246 252
247 253 sent=self.sendEmail(email_from=self.__emailFromAddress,
248 254 email_to=self.__emailToAddress,
249 255 subject=subject,
250 256 message=message,
251 257 subtitle=subtitle,
252 258 filename=filename)
253 259
254 260 if sent:
255 261 print "***** Your system administrator has been notified *****"
256 262
257 263
258 264 def notify(self, email, message, subject = "", subtitle="", filename=""):
259 265 """notify sends an email with the given message and title to email.
260 266
261 267 Inputs: email (string), message (string), and subject (string)
262 268
263 269 Returns: void
264 270
265 271 Affects: none
266 272
267 273 Exceptions: None.
268 274 """
269 275
270 276 print "Notifying to %s ..." %email
271 277
272 278 self.sendEmail(email_from=self.__emailFromAddress,
273 279 email_to=email,
274 280 subject=subject,
275 281 message=message,
276 282 subtitle=subtitle,
277 283 filename=filename)
278 284
279 285 print "***** Your system administrator has been notified *****"
280 286
281 287 class SchainError(Exception):
282 288 """SchainError is an exception class that is thrown for all known errors using Schain Py lib.
283 289
284 290 Usage example:
285 291
286 292 import sys, traceback
287 293 import schainpy.admin
288 294
289 295 try:
290 296
291 297 test = open('ImportantFile.txt', 'r')
292 298
293 299 except:
294 300
295 301 raise schainpy.admin.SchainError('ImportantFile.txt not opened!',
296 302 traceback.format_exception(sys.exc_info()[0],
297 303 sys.exc_info()[1],
298 304 sys.exc_info()[2]))
299 305 """
300 306
301 307
302 308 def __init__(self, strInterpretation, exceptionList=None):
303 309 """ __init__ gathers the interpretation string along with all information from sys.exc_info().
304 310
305 311 Inputs:
306 312 strIntepretation - A string representing the programmer's interpretation of
307 313 why the exception occurred
308 314
309 315 exceptionList - a list of strings completely describing the exception.
310 316 Generated by traceback.format_exception(sys.exc_info()[0],
311 317 sys.exc_info()[1],
312 318 sys.exc_info()[2])
313 319
314 320 Returns: Void.
315 321
316 322 Affects: Initializes class member variables _strInterp, _strExcList.
317 323
318 324 Exceptions: None.
319 325 """
320 326
321 327 if not exceptionList:
322 328 exceptionList = traceback.format_exception(sys.exc_info()[0],
323 329 sys.exc_info()[1],
324 330 sys.exc_info()[2])
325 331
326 332 self._strInterp = strInterpretation
327 333 self._strExcList = exceptionList
328 334
329 335
330 336 def getExceptionStr(self):
331 337 """ getExceptionStr returns a formatted string ready for printing completely describing the exception.
332 338
333 339 Inputs: None
334 340
335 341 Returns: A formatted string ready for printing completely describing the exception.
336 342
337 343 Affects: None
338 344
339 345 Exceptions: None.
340 346 """
341 347 excStr = ''
342 348 excStr = excStr + self._strInterp + '\n\n'
343 349
344 350 if self._strExcList != None:
345 351 for item in self._strExcList:
346 352 excStr = excStr + str(item) + '\n'
347 353
348 354 return excStr
349 355
350 356 def __str__(self):
351 357
352 358 return(self.getExceptionStr())
353 359
354 360
355 361 def getExceptionHtml(self):
356 362 """ getExceptionHtml returns an Html formatted string completely describing the exception.
357 363
358 364 Inputs: None
359 365
360 366 Returns: A formatted string ready for printing completely describing the exception.
361 367
362 368 Affects: None
363 369
364 370 Exceptions: None.
365 371 """
366 372
367 373 excStr = '<BR>The following Schain Python exception has occurred:\n<BR>'
368 374 excStr = excStr + self._strInterp + '\n<BR>\n'
369 375
370 376 if self._strExcList != None:
371 377 for item in self._strExcList:
372 378 excStr = excStr + str(item) + '\n<BR>'
373 379
374 380 return excStr
375 381
376 382 if __name__ == '__main__':
377 383
378 384 test = SchainNotify()
379 385
380 386 test.sendAlert('This is a message from the python module SchainNotify', 'Test from SchainNotify')
381 387
382 388 print 'Hopefully message sent - check.'
General Comments 0
You need to be logged in to leave comments. Login now