INTELLIGENT ENVIRONMENT
  • Home
  • About
  • PROJECTS
  • Contact

Python

e_MailMan -

As I said, many programs can be created that make things a multi functional example. "Magic Mirror" can be a secret home guard. It needs to be improved. Built-in motion detection, web camera. I still think I'd be fine - a microphone. I thought it would be interesting to know about the coming email  should not leave the mail open.  I will use Raspberry Pi3 to process the application. All information about "haw you can make ... I find in internet. Few moment find in  this web page "How to". e-MailMan program I split in few stages. Wen I learning how to realize my idea I notice, Internet network is a must for successful implementation of the idea. Also need files for e-mail credential storage.This led to the need for another code...

So, let's start

First file who checked needs parameters is start_prog.py
, hide_password.py source create needs file, and last gmail_request.py. checked email.

start_prog.py
#!/usr/bin/python
from tkinter import *
import os
import sys
import time
import requests
import pathlib
import threading


Importing all needs library, tkinter for GUI, os and sys for collaborating with OS (Windows or Linux), time - if need function when call time function, requests- web page, pahlib - searching OS file system, threading - manipulation with source.

window = Tk()
page_link= ('https://www.google.com')

Page link use for Internet connection control.

window.geometry('600x100+650+550')
window.title('Informational message')


var=StringVar()

String Var use for information messages text changes

msg=Label(window,textvar=var, fg = 'black', font = "times 22")
msg.pack(padx=5, pady=10)


def request_mail():
    threading.Timer(1200.0, request_mail).start()
    os.system('python /root/Desktop/request_gmail.py')


This function restarting .py file every 20 minutes

def no_access3():
    var.set('Check yuo network and try again')
    msg.update_idletasks()
    msg.destroy()
    time.sleep(3)
    window.destroy()


 msg.destroy-clear messages,window.destroy-close GUI (tkinter) 

def no_access():
    var.set('ERROR, no internet access')
    msg.update_idletasks()
    time.sleep(3)
    no_access3()

    
def wlan_ok3 ():
    file = pathlib.Path("setings_mirror.txt.enc")
    if file.exists ():
        var.set("All file exist\n start e-MailMan!")
        msg.update_idletasks()
        time.sleep(3)
        window.destroy()
        request_mail()
    else:
        var.set("No requare file exsist!")
        msg.update_idletasks()
        time.sleep(3)
        window.destroy()
        os.system('python /root/Desktop/to_line.py')

    
def wlan_ok2 ():
    
    file = pathlib.Path("setings_mirror.txt")
    if file.exists ():
        var.set("Start search requar files\n on machine!")
        msg.update_idletasks()
        time.sleep(3)
        wlan_ok3()

    else:
        var.set("No requare file exsist!\n create new")
        msg.update_idletasks()
        time.sleep(3)
        window.destroy()
        os.system('python /root/Desktop/to_line.py')

    
def wlan_ok1 ():
    var.set('Find internet connection')
    msg.update_idletasks()
    time.sleep(3)
    wlan_ok2 ()


def check_wlan():
    try:
        while True:
            page_rsp= requests.get(page_link,timeout=10)
            if page_rsp.status_code==200:

                # here we can put code to event log
                wlan_ok1()
                break                   
    except requests.exceptions.ConnectionError:
        pass
        no_access()


def start_asistant ():
    var.set('Hello \n check system..')
    msg.update_idletasks()
    time.sleep(3)
    check_wlan()


start_asistant()

window.mainloop()

About password safety (as a security analyst :)) we will talk in another page, because  then coding CRYPTOGRAPHY. Use library simplecrypt import encrypt, decrypt.

gmail_request.py


import time
import imaplib
import email
from tkinter import *

from tkinter import messagebox
from simplecrypt import encrypt, decrypt
import os

decrypt_word = 'Inteligently'


For safety change this word in what do you want like "1nT3l1g3ntly", and .txt file name to.

data_file = 'setings_mirror.txt'

window = Tk()
window.configure(background = 'black')
window.after(30000,lambda:window.destroy())

window.geometry('1050x150+950+1010')
window.title('Information messages')

mail_icon = PhotoImage(file = '/root/Desktop/mail.png')

msg_line1=''

msg_frame = Frame(window, bg = 'black')
msg_frame.grid(row = 0, column = 0)

frame_png = Frame (msg_frame,bg = 'black')
frame_png.grid(row = 0, column = 0)

frame_txt = Frame(msg_frame, bg = 'black')
frame_txt.grid(row = 0, column = 1)

msg0 = Label (frame_png, image = mail_icon, bg = 'black')
msg0.grid()

line_msg = Label (frame_txt, font = "times 22", bg ='black', fg = 'white')
line_msg.grid(sticky = W)

class credent:
    global decrypt_word
    
    def __init__(self):
        f = open(data_file, 'r')
        for line in f:
            columns = line.split()
            self.imap=columns[0]
            self.user = columns[1]
            with open('setings_mirror.txt.enc', 'rb') as openpass:
                 s_pasw = openpass.read()
                 self.password = decrypt(decrypt_word, s_pasw)
    
def email_credent():
        return credent()
cred = email_credent()

IMAPSERVER = cred.imap
USER = cred.user
PASSWORD = cred.password

def my_email():
        global msg_line1
   try:
        mail = imaplib.IMAP4_SSL(IMAPSERVER)
        mail.login(USER, PASSWORD)
        mail.select("INBOX", True)
        return_code, mail_ids = mail.search(None, 'UNSEEN')
                      
        if mail_ids == ['']:
            count = 0
        else:
            count = len(mail_ids[0].split(' '))
    except:
        count = 0
        pass
        
    try:
        result, mail_id = mail.search(None, 'ALL')
        ID = mail_id[0]
        if ID == 0:
            pass
        else:
            id_list = ID.split(' ')
            latest_email_id = id_list[-1]
        
            result, data = mail.fetch(latest_email_id, "(RFC822)")
            raw_email = data[0][-1]
            raw_email_string = raw_email.decode('UTF-8')
#ASCII' #CP1257'  # 'iso-8859-13'
            email_message = email.message_from_string(raw_email_string)

 
Tray to find correct decode messages header, but.....                     

            msg_line = "You have: {0:4}, e-mail \nUnread: {1:4}, e-mail \nThe last From :  {2:20}" .format(latest_email_id, count, email_message['From'])

Format messages line text.
            
            if msg_line != msg_line1:
                msg_line1 = msg_line
            line_msg.config(text = msg_line)

This cycle for update information on messages.            

    except:
        ID = 0
        pass
        msg_no = Label (window, text="No New@Messages", font="times 22")
        msg_no.grid(row = 0, column = 1)
   
my_email()

window.mainloop()

This .py source help you put e-mail parameters in file and hide password file

hide_pasword.py

from tkinter import *
from tkinter import messagebox
from simplecrypt import encrypt, decrypt
import os

decrypt_word = 'Inteligently'
data_file = 'setings_mirror.txt'

message_gui = Tk()
message_gui.geometry('400x110+650+450')
message_gui.title('Setings parametres')

Label(message_gui, text=" IMAP server").grid(row=0, sticky = W)
Label(message_gui, text=" e-mail address").grid(row=1, sticky = W)
Label(message_gui, text=" Password  ").grid(row=2, sticky = W)

button_frame = Frame()
button_frame.grid(row =3, column = 1)

entry_window1 = Entry(message_gui, width=30)
entry_window1.grid(row=0, column=1)
entry_window2 = Entry(message_gui, width=30)
entry_window2.grid(row=1, column=1)
entry_window3 = Entry(message_gui, show ='*', width=30)
entry_window3.grid(row=2, column=1)

def show_message():
    messagebox.showwarning("Settings fields", "Not enough parameter")

def clear():
    entry_window1.delete(0, END)
    entry_window2.delete(0, END)
    entry_window3.delete(0, END)

def setings_fields():
   
   global decrypt_word
   global hide_pasw
   
   if not entry_window3.get():
      show_message()
      return
   if entry_window3 == '':
      show_message()
      return        
   else
:
      
      setings_file = open(data_file, 'a')
      setings_file.write("%s\t%s " % (entry_window1.get(), entry_window2.get()))
      
      crypt_data = entry_window3.get()
      hide_pasword=encrypt(decrypt_word, crypt_data)
      with open(data_file + ".enc", 'wb') as secret:
        secret.write(hide_pasword)
        secret.close()
        setings_file.close()
        message_gui.quit()
        time.sleep(3)
        os.system('python /root/Desktop/start_prog.py')
   
def open_pasw():
   global decrypt_word  
   f = open(data_file, 'r')
   for line in f:
      columns = line.split()
      imap=columns[0]
      addr = columns[1]
      
      with open('setings_mirror.txt.enc', 'rb') as openpass:
        pasw = openpass.read()
        dec_pass = decrypt(decrypt_word, pasw)
        print ("Password is: %s" % dec_pass, imap, addr)

def deleteContent():
   with open(data_file, "w"):
        pass
   if os.path.exists('setings_mirror.txt.enc'):
      messagebox.showwarning("Setings file", "All data in file will be erased")
      with open('setings_mirror.txt.enc', "w"):
        pass
      os.remove('setings_mirror.txt.enc')
   else:
      messagebox.showwarning("File missing", "The pasword file not exists, must create file")


deleteContent()

quit_button = Button(button_frame,text='Quit', command=message_gui.quit).grid(row = 3, column = 0, sticky = W)
save_button = Button(button_frame, text='Save', command=setings_fields).grid(row = 3, column = 1, sticky = W)
clear_button = Button(button_frame, text="Clear", command=clear).grid(row = 3, column = 2, sticky = W)
#show_pasw = Button(button_frame, text="Pasw", command=open_pasw).grid(row = 3, column = 3, sticky = W)

The "Pasw" button  has been turned off because, his function show password in plain text. Can change function
 when after push button password send in you email, but i think it is not needed.


message_gui.mainloop( )
     

 This source is probably over, I think some things do better with this code. First - hide the breath password. Password is a very important word for you security. Secondly, this code executes repetitive update information from email. Mail server. Third - Email Notifications Mail will be hidden after "N" time.
mail.png
File Size: 5 kb
File Type: png
Download File

Lesson
Powered by Create your own unique website with customizable templates.
  • Home
  • About
  • PROJECTS
  • Contact