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