Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
updates for settings tab in web UI
  • Loading branch information
jgyates authored Feb 11, 2018
1 parent a23f018 commit 7f9d39b
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 8 deletions.
82 changes: 82 additions & 0 deletions genserv.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from flask import Flask, render_template, request, jsonify, session
import sys, signal, os, socket, atexit, configparser
import mylog, myclient
import urlparse
import re

#------------------------------------------------------------
app = Flask(__name__,static_url_path='')
Expand Down Expand Up @@ -77,9 +79,88 @@ def ProcessCommand(command):
log.error("Error on command function" + str(e1))
return jsonify(data)

elif command in ["settings"]:
data = GetSettings()
return jsonify(data)

elif command in ["setsettings"]:
# SaveSettings((request.args.get('setsettings', 0, type=str)));
SaveSettings(request.args.get('setsettings', 0, type=str));
return "OK"

else:
return render_template('command_template.html', command = command)

#------------------------------------------------------------
def GetSettings():

allSettings = {"disableemail" : ['boolean', 'Disable Email usage', 1], "email_pw" : ['string', 'Email Password', 3], "email_account" : ['string', 'Email Account', 2], "sender_account" : ['string', 'Sender Account', 4], "email_recipient" : ['string', 'Email Recepient<br><small>(comma delimited)</small>', 5], "smtp_server" : ['string', 'SMTP Server <br><small>(leave emtpy to disable)</small>', 6], "imap_server" : ['string', 'IMAP Server <br><small>(leave emtpy to disable)</small>', 7], "smtp_port" : ['int', 'SMTP Port', 8], "ssl_enabled" : ['boolean', 'SSL Enabled', 9]}

settings = configparser.RawConfigParser()
# config parser reads from current directory, when running form a cron tab this is
# not defined so we specify the full path
settings.read('/etc/mymail.conf')

# heartbeat server port, must match value in check_generator_system.py and any calling client apps
for setting in allSettings.keys():
if settings.has_option('MyMail', setting):
allSettings[setting].append(settings.get('MyMail', setting))

return allSettings

#------------------------------------------------------------
def SaveSettings(query_string):
settings = dict(urlparse.parse_qs(query_string, 1))

try:
# Read contents from file as a single string
file_handle = open("/etc/mymail.conf", 'r')
file_string = file_handle.read()
file_handle.close()

# Write contents to file.
# Using mode 'w' truncates the file.
file_handle = open("/etc/mymail.conf", 'w')
for line in file_string.splitlines():
if not line.isspace():
for setting in settings.keys():
parts = findConfigLine(line)
if (parts and (len(parts) > 4) and (parts[1] == setting)):
if (len(parts[3]) >= 3):
line = line.replace(parts[3], settings[setting][0], 1)
else:
myList = list(parts)
myList[3] = settings[setting][0]
line = "".join(myList)
file_handle.write(line+"\n")
file_handle.close()

except Exception as e1:
print "Error Update Config File: " + str(e1)
log.error("Error Update Config File: " + str(e1))

def findConfigLine(line):
match = re.search(
r"""^ # Anchor to start of line
(\s*) # $1: Zero or more leading ws chars
(?: # Begin group for optional var=value.
(\S+) # $2: Variable name. One or more non-spaces.
(\s*=\s*) # $3: Assignment operator, optional ws
( # $4: Everything up to comment or EOL.
[^#\\]* # Unrolling the loop 1st normal*.
(?: # Begin (special normal*)* construct.
\\. # special is backslash-anything.
[^#\\]* # More normal*.
)* # End (special normal*)* construct.
) # End $4: Value.
)? # End group for optional var=value.
((?:\#.*)?) # $5: Optional comment.
$ # Anchor to end of line""",
line, re.MULTILINE | re.VERBOSE)
if match :
return match.groups()
else:
return []

#------------------------------------------------------------
if __name__ == "__main__":
Expand Down Expand Up @@ -141,3 +222,4 @@ def ProcessCommand(command):

except Exception as e1:
log.error("Error in app.run:" + str(e1))

27 changes: 19 additions & 8 deletions mymail.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def __init__(self, monitor = False, incoming_folder = None, processed_folder = N
self.Mailbox = 0
self.EmailSendQueue = [] # queue for email to send
self.DisableEmail = False
self.SSLEnabled = False

# log errors in this module to a file
if localinit == True:
Expand All @@ -55,12 +56,18 @@ def __init__(self, monitor = False, incoming_folder = None, processed_folder = N

self.EmailPassword = config.get('MyMail', 'email_pw')
self.EmailAccount = config.get('MyMail', 'email_account')
if config.has_option('MyMail', 'sender_account'):
self.SenderAccount = config.get('MyMail', 'sender_account')
else:
self.SenderAccount = self.EmailAccount
self.EmailRecipient = config.get('MyMail', 'email_recipient')
self.SMTPServer = config.get('MyMail', 'smtp_server')
self.IMAPServer = config.get('MyMail', 'imap_server')
self.SMTPPort = config.getint('MyMail', 'smtp_port')
if config.has_option('MyMail', 'disableemail'):
self.DisableEmail = config.getboolean('MyMail', 'disableemail')
if config.has_option('MyMail', 'ssl_enabled'):
self.SSLEnabled = config.getboolean('MyMail', 'ssl_enabled')
except Exception as e1:
self.FatalError("ERROR: Unable to read config file" + str(e1))

Expand Down Expand Up @@ -176,7 +183,7 @@ def sendEmailDirectMIME(self, subjectstr, msgstr, recipient = None, files=None,
tmstamp=datetime.datetime.now().strftime('%I:%M:%S %p')

msg = MIMEMultipart()
msg['From'] = self.EmailAccount
msg['From'] = self.SenderAccount
msg['To'] = recipient
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subjectstr
Expand All @@ -202,20 +209,24 @@ def sendEmailDirectMIME(self, subjectstr, msgstr, recipient = None, files=None,
except Exception as e1:
self.LogError("Error attaching file in sendEmailDirectMIME: " + str(e1))

session = smtplib.SMTP(self.SMTPServer, self.SMTPPort)
session.ehlo()
session.starttls()
self.LogError("Loggin in 0 "+self.SMTPServer+":"+str(self.SMTPPort))
if self.SSLEnabled:
session = smtplib.SMTP_SSL(self.SMTPServer, self.SMTPPort)
session.ehlo()
else:
session = smtplib.SMTP(self.SMTPServer, self.SMTPPort)
session.starttls()
session.ehlo
# this allows support for simple TLS

session.ehlo
# this allows support for simple TLS
if self.EmailPassword != "":
session.login(self.EmailAccount, self.EmailPassword)

if "," in recipient:
multiple_recipients = recipient.split(",")
session.sendmail(self.EmailAccount, multiple_recipients, msg.as_string())
session.sendmail(self.SenderAccount, multiple_recipients, msg.as_string())
else:
session.sendmail(self.EmailAccount, recipient, msg.as_string())
session.sendmail(self.SenderAccount, recipient, msg.as_string())
session.quit()
# end sendEmail()

Expand Down

0 comments on commit 7f9d39b

Please sign in to comment.