Advertisement
Guest User

Gryff Priest DSDB

a guest
Jul 19th, 2016
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.10 KB | None | 0 0
  1. from tkinter import * #import the entire tkinter module
  2. import imaplib #import IMAP based email utilities
  3. import email #other useful universal email utilities
  4. import email.header #a specific email utility pertaining to the subject
  5. import pymysql #Python mysql connector/support, the official one didn't install properly
  6. import datetime #Date and time utilities
  7.  
  8.  
  9. connection = pymysql.connect(host="localhost", #All this is the configuration for connecting to the MySQL Database
  10.                              port=3306,
  11.                              user="root",
  12.                              passwd="",
  13.                              db="dollarsolardb")
  14.  
  15. cursor = connection.cursor() #Allows the insertion of SQL commands
  16.  
  17.  
  18. INBOX = "INBOX" #Simply creates INBOX in the form of a string as the function doesn't accept it
  19.  
  20. name = [] #Creates a list for the names generated later
  21. phone = [] #Creates a list for the phones generated later
  22. postcode = [] #Creates a list for the postcodes generated later
  23. email_address = [] #Creates a list for the email_addresses generated later
  24. message = [] #Creates a list for the messages generated later
  25.  
  26. def AddData(name,postcode,phone,email_address,message): #creates the function that the Add to DB button runs
  27.     command = "INSERT INTO customerinfo(name,postcode,phone,email_address,message) ""VALUES(%s,%s,%s,%s,%s)" #This is the SQL command
  28.     data = (name,postcode,phone,email_address,message) #An easy way of encapsulating all the data from the lists
  29.     cursor.execute(command, data) #Tells the cursor to run the SQL command
  30.     connection.commit() #Saves the changes to the databases
  31.  
  32.  
  33. def LoginValidate(): #The first command that is run by a button, it logs in to the IMAP system
  34.     success = 1 #Stores whether the login attemp was successful
  35.     try: #This try command basically gives room for error when running something, the application will continue after doing a special set of commands
  36.         short.login(entryUsername.get(), entryPassword.get()) #Runs the IMAP login command
  37.     except short.error: #If the login command returns an error, do:
  38.         success = 0 #Success = 0 because logging in didn't work
  39.     if success == 1:
  40.         MainWindow()#Open the next window
  41.     else:
  42.         entryUsername.delete(0,END) #Clear the email entry
  43.         entryUsername.insert(0,"ERROR, CAN'T LOG IN") #fill it with an error message
  44.  
  45. def Logout(): #hypothetically the last command, it closes and logs out of everything, email, sql etc.
  46.     connection.close() #close the mysql connection
  47.     try:
  48.         short.close() #try the close the email inbox
  49.     except short.error:
  50.         labText.set("logouterror, please close the app conventially") #This should occur if the user tries to logout without opening an inbox, nothing really wrong
  51.     short.logout() #logs out of the IMAP system
  52.     mWindow.destroy() #closes the mainwindow
  53.     root.destroy() #closes the login window
  54.  
  55. def LoginShort(event): #This function only exists due to quirky tkinter syntax, if a function is given an argument (event) tkinter will run it in the config and break
  56.     LoginValidate() #this is the Logincommand, thats all this does
  57.  
  58.  
  59. def ButtonCommand(): #Similary to the other command, as the function takes an argument, it needs a command to run it
  60.     EmailGet(short) #runs the emailget command
  61.  
  62.  
  63. def EmailGet(short): #command that fetches the specific emails
  64.     check, blank = short.select(INBOX) #The IMAP select command selects the INBOX letterbox
  65.     if check != "OK": #it returns a status value, if everything is good it returns "OK", this checks if it is was OK
  66.         labText.set("No inbox!") #Gives an error status
  67.    
  68.     if  boxTime.get() == "One Day": #Finds the selected time range, creates a variable for each range in day
  69.         dayrange = 1
  70.     elif boxTime.get() == "One Week":
  71.         dayrange = 7
  72.     elif boxTime.get() == "30 Days":
  73.         dayrange = 30
  74.     elif boxTime.get() == "One Year":
  75.         dayrange = 365
  76.  
  77.              
  78.     check, emails = short.search(None, '(SUBJECT "Dollar Solar Website Contact Form Submission")') #IMAP SEARCH command, selects emails with a specific value, in this case, those with a certain subject
  79.     if check != "OK":
  80.         labText.set("No emails!") #Shows an error message
  81.     email_list = emails[0].split() #creates a list from the returned values of the SEARCH command
  82.     for i in email_list: #iterates through the emails in email_list
  83.         check, email_info, = short.fetch(i, '(RFC822)') #IMAP FETCH command, fetches the specific info of the email, the meat if you will
  84.         if check != "OK":
  85.             labText.set("Cannot extract email data")
  86.         else: #If the command returns  an all good
  87.             details = email.message_from_bytes(email_info[0][1]) #the internal data in the email
  88.             details_date = email.utils.parsedate_tz(details['Date']) #the date of email arrival
  89.  
  90.             datelist = [] #its an empty list of the dates
  91.             datelist.append(details_date[0:3]) #adds the Year Month and Day to the list
  92.  
  93.             date_year = (int(details_date[0])) #splits up the year month and day
  94.             date_month = (int(details_date[1]))
  95.             date_day = (int(details_date[2]))
  96.            
  97.             datedays = datetime.date(date_year,date_month,date_day) #Changes all those in to a datetime format
  98.             todaydate = datetime.date.today() #todays date in datetime format
  99.  
  100.             if abs(todaydate-datedays).days >= dayrange: #if the absolute value of the two dates is greater than the specified date range, then it is too old
  101.                 within_daterange = False
  102.             else:
  103.                 within_daterange = True
  104.                 for part in details.walk(): #runs through the email and puts each part on a new line
  105.                     if part.get_content_type() == 'text/plain': #if the each part is normal text
  106.                         emailDisplay.insert(END, part.get_payload()) #Insert each part of the email in to the textbox, line by line
  107.     buttonAdd.config(state="normal") #Allows the button that adds the text to the database to be pressed, considering there is actually text now      
  108.     labText.set("Everything ok!, please edit the text if necassary. When completed click the 'Add to DB'") #further instruction to the user        
  109. def DB_ADD(): #function that adds whats in the text box to the database
  110.     for line in emailDisplay.get(1.0,'end-1c').splitlines(): #iterate through each line in the textbox (1.0 = first character, 'end-1c' = last
  111.                             if line[0:10] == "Your Name:": #if the first 10 characters are "Your Name:" add the rest of the line to the list
  112.                                 name.append(line[11:])
  113.                             elif line[0:12] == "> Your Name:": #These lines are more or less the same, with different character lengths and words...
  114.                                 print(line[13:])
  115.                                 name.append(line[13:])
  116.                             elif line[0:12] == "*Your Name*:":
  117.                                 print(line[13:])
  118.                                 name.append(line[13:])
  119.                            
  120.                             if line[0:6] == "Phone:":
  121.                                 print(line[7:])
  122.                                 phone.append(line[7:])
  123.                          
  124.                             elif line[0:8] == "> Phone:":
  125.                                 print(line[9:])
  126.                                 phone.append(line[9:])
  127.                      
  128.                             elif line[0:8] == "*Phone*:":
  129.                                 print(line[9:])
  130.                                 phone.append(str(line[9:]))
  131.                          
  132.  
  133.                             if line[0:9] == "Postcode:":
  134.                                 print(line[10:])
  135.                                 postcode.append(line[10:])
  136.                        
  137.                             elif line[0:11] == "> Postcode:":
  138.                                 print(line[12:])
  139.                                 postcode.append(line[12:])
  140.                          
  141.                             elif line[0:11] == "*Postcode*:":
  142.                                 print(line[12:])
  143.                                 postcode.append(line[12:])
  144.                          
  145.                             if line[0:19] == "Your Email Address:":
  146.                                 print(line[20:])
  147.                                 email_address.append(line[20:])
  148.                                
  149.                             elif line[0:21] == "> Your Email Address:":
  150.                                 print(line[22:])
  151.                                 email_address.append(line[22:])
  152.                              
  153.                             elif line[0:21] == "*Your Email Address*:":
  154.                                 print(line[22:])
  155.                                 email_address.append(line[22:])
  156.                                
  157.  
  158.                             if line[0:8] == "Message:":
  159.                                 print(line[9:])
  160.                                 message.append(line[9:])
  161.                            
  162.                             elif line[0:10] == "> Message:":
  163.                                 print(line[11:])
  164.                                 message.append(line[11:])
  165.                              
  166.                             elif line[0:10] == "*Message*:":
  167.                                 print(line[11:])
  168.                                 message.append(line[11:])
  169.  
  170.                            
  171.                            
  172.     print(name) #these are pretty much diagnostic just print the lists to make sure everything has worked
  173.     print(phone)
  174.     print(postcode)
  175.     print(email_address)
  176.     print(message)
  177.  
  178.     iterate = 0 #A helper for the next line just a value that counts how many times it has looped
  179.    
  180.     for number in name: #for each value in name (and hypothetically every other list),
  181.         AddData(name[iterate], postcode[iterate],phone[iterate], email_address[iterate], message[iterate]) #run the add data function with the values as arguments
  182.         iterate = iterate + 1 #add 1 to iterate so we don't add the same data again
  183.     labText.set("Added "+str(iterate)+" emails to DB") #confirmation to the user
  184. def MainWindow(): #this funcion is the window that opens after logging in
  185.     global mWindow #global makes variables callable in all functions, otherwise it would error if it was referenced
  186.     mWindow = Toplevel(root) #creates a new window
  187.     mWindow.minsize(width=600, height=400) #defines the size of the window
  188.     mWindow.title("Dollar Solar Database Manager") #names the window
  189.  
  190.     global labStatus
  191.     global labText
  192.     labText = StringVar()
  193.     labText.set("Logged in successfully, awaiting processing...")
  194.     labStatus = Label(mWindow, textvariable = labText, fg=("green")) #creates text that explains to the user what is going on
  195.     labStatus.grid(row=0, sticky=W) #positions it
  196.  
  197.     labGuidance = Label(mWindow, text="Please select a time range, and click the button") #tells the user what to do
  198.     labGuidance.grid(row=1, sticky=W)
  199.  
  200.     global boxTime
  201.     boxTime = Spinbox(mWindow,values=("One Day", "One Week", "30 Days", "One Year"), state="readonly") #creates the menu where the user can select a time range
  202.     boxTime.grid(row=2, column=0, sticky=W)
  203.    
  204.     buttonFetch = Button(mWindow, text = ("Fetch Emails"), command=ButtonCommand) #creates a button that executes the email fetch function
  205.     buttonFetch.place(x=135,y=40) #an alternate and more exact, if not more finnicky form of placement
  206.  
  207.     global buttonAdd
  208.     buttonAdd = Button(mWindow, text = ("Add to DB"), command=DB_ADD, state=DISABLED) #creates a button that executes the add to DB function, initially disabled
  209.     buttonAdd.place(x=220, y=40)
  210.  
  211.     buttonQuit = Button(mWindow, text = "Logout/Quit", command=Logout) #button that executes the logout function
  212.     buttonQuit.place(x=565, y=40)
  213.  
  214.     global emailDisplay
  215.     emailDisplay = Text(mWindow, fg="gray", wrap=WORD) #this creates the textbox that holds the email data, it is editable for changes
  216.     emailDisplay.grid(row=3, column=0, sticky=W)
  217.  
  218.     scroller = Scrollbar(mWindow) #this creates the scrollbar for the text display, why it has to be its own widget, well I'm not sure
  219.     scroller.grid(row=3,column=0,sticky=N+E+S)
  220.  
  221.     emailDisplay.config(yscrollcommand=scroller) #tells the textbox to listen to the scrollbar
  222.     scroller.config(command=emailDisplay.yview) #tells the scrollbar where it belongs
  223.    
  224.        
  225. short = imaplib.IMAP4_SSL("imap.gmail.com") #This variable is simply an abbreviation of the IMAPLIB commands, so I don't have to type it every time I want to use it
  226. #note the SSL for safe travel of the data
  227.  
  228. root = Tk() #creates the login window
  229. root.title("Dollar Solar Database Manager") #names the window
  230. root.maxsize(width=600, height=350) #sets the size
  231.  
  232. loginmessage = Label(root, text = "Please Log In", font=("Cambria",28)) #creates the original instruction
  233. loginmessage.grid(row=0, sticky=N)
  234.  
  235. labUsername = Label(root, text = ("EMAIL:")) #tells the user where to put their details
  236. labUsername.grid(row=1, sticky =W)
  237.  
  238. global entryUsername
  239. entryUsername = Entry(root, text = ("")) #creates the entry where the user enters their details
  240. entryUsername.grid(row=1, column =0, sticky=E)
  241. entryUsername.bind("<Return>",LoginShort) #the bind function enables certain keys to be able to perform actions in certain widgets, in this case it does the same thing as hitting the button
  242.  
  243. labPassword = Label(root, text = ("PASSWORD:")) #tells the user where to put their details
  244. labPassword.grid(row=2, sticky=W)
  245.  
  246. entryPassword = Entry(root, text = (""),show="*") #where the user puts their password, it shows asterisks (*) so no cheeky people look over their shoulder"
  247. entryPassword.grid(row=2, column =0, sticky=E)
  248. entryPassword.bind("<Return>",LoginShort)
  249.  
  250. buttonConfirm = Button(root, text = ("LOGIN"), command=LoginValidate) #Attempts to log the user in using the LoginValidate function
  251. buttonConfirm.grid(row =1,column =1, sticky=E)
  252.  
  253.  
  254. root.mainloop() #Creates the loop that maintains the tkinter windows, necassary for a working application
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement