CodingHighlevel

SMTP Email WebApplication with Python

Reference :Email server of Chap5

Introduction :

SMTP Email with Python WebApplication: In this manipulation the code is designed for the web application server to receive a POST or a GET request from the low structure Microcontroller like the Arduino and to store the provided data in the SQLite database and send a Gmail SMPT Email;

Technologies :

  • Email (SMPT)
  • JSON
  • HtSQL
  • python

Methodology :

  • Testing the Database and visualise its content form the client side.
  • Sent a Empty notification Email in responce to a GET http request (ex: sent from the Microcointroller Ethernet sheild).+ Store the data
  • Visualise sent a Compet notification(can include attachement) Email in responce to a GET http request (ex: sent from the Microcointroller Ethernet sheild). Store the data in the data base;

Database connection testing via HtSQL:

HtSQL provide the option visualize and manipulate the SQLite database from the client side over the browser, without logging into the server.

HtSQL Server side:

First create and populate the database and then Just provide the full path of the SQLile that you want to point.

htsql-ctl server 'sqlite:<Path>/controlP.db'

HtSQL Client side:

HtSQL service test :

http://<Server_iP>:8080/

Database conncetion test and visualize some tables in he database :

http://<Server_IP>:8080/Parcel   

The content visualization of the table “Parcel” from theponted DataBase.

The content visualization of the table “Parcel” from theponted DataBase.

The server concole after responding the Client’s requests.

The server concole after responding the Client’s requests.

Now that we made sure that database communication is well established and working well, let’s launch the Server Script.

Execution Server side:

The objectif of of the server code is to receive the clients http/text or http/json requests and send an email accordently :

In case of :

  • Http/Text requests, server will send just a plae test notify to the client browser that means it’s working properly “Parcel sensor service running!” then send an Email with a plane text “….From GET : \nServer is running !!”
  • Http/Json requests, server will traite the JSON resqust and extract the the data of interest, then insert the data into the database and finaly send a notification Email.

Making the scripte excutable; the code is listed in the end of the page.

chmod +x EmailServerChap5.py

Run the scripte server as service:

./EmailServerChap5.py&

Execution GET:(Response to Http/text request )

Client side:

http://<Server_IP>:8081/Parcel   

Result :

The client’s in response to the Http/text Request:

The client’s in response to the Http/text Request.

SMTP Gmail mail sent in in response to the Http/text Request.

SMTP Gmail mail sent in in response to the Http/text Request.

Execution POST: (Response to JSON request )

Client POST request :

Postman Software

Javescript XHR json request to send :

var data = JSON.stringify({
"room": "2"
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://<Server_iP>:8081?\"room\"='1'&%22room%22=%271%27");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("Postman-Token", "3361331f-0c97-4f5d-8cb1-7f39c616a076");
xhr.send(data);

Formated json Post request:

{"room": "2"
}

Explication :

data_string = cgi.parse_qs(self.rfile.read(int(self.headers['Content-Length'])), keep_blank_values=1)
room = json.loads(data_string.keys()[0])['room']

Result POST :

The whole Code :

#!/usr/bin/env python
import sqlite3
import smtplib
import cgi
import json
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from email.mime.text import MIMEText
class RequestHandler(BaseHTTPRequestHandler):
	def do_GET(self):
		self.send_response(200)
		self.send_header('Content-type','text/html')
		self.end_headers()
		self.wfile.write("Parcel sensor service running!")
		self.send_mail("From GET : \nServer is running !!")
		return
	def do_POST(self):
		data_string = cgi.parse_qs(self.rfile.read(int(self.headers['Content-Length'])), keep_blank_values=1)
		room = json.loads(data_string.keys()[0])['room']
		my_query = 'INSERT INTO Parcel(RoomID,Datetime) \
		           VALUES(%s,CURRENT_TIMESTAMP);' %(room)
		try:
			connection = sqlite3.connect('/home/pi/database/EmailserverChap5/controlP.db',isolation_level=None)
			cursor = connection.cursor()
			cursor.execute(my_query)
			query_results = cursor.fetchone()
			my_response = "New parcel delivered to room ID %s" %(room)
			self.send_mail("From Post \n"+my_response)
		except sqlite3.Error, e:
			my_response = "There is an error %s:" % (e)
		finally:
			print my_response
			connection.close()

	def send_mail(self,d=""):
		""" 
		smtpUser = 'xxxxxx@gmail.com'
		smtpPass = 'xxxxxxx'
		fromAdd  = smtpUser
		toAdd    = 'xxxxxxxxxxxxxxxx@gmail.com'
		subject = 'Parcel Updates'
		header  = 'To:'      + toAdd   + '\n' \
				+ 'From: '   + fromAdd + '\n' \
				+ 'Subject: '+ subject
		body    = 'From within a Python script / Methode : '+ d + '\n'
		print header + '\n' + body 
		"""
		sender = 'xxxxxxxxxxx@gmail.com'
		receivers = [sender]
		password = 'xxxxxxxxx'
		fromad = 'Raspberry Pi Parcel Sensor <xxxxxxxxxxx@gmail.com>'
		toad = 'Name <xxxxxxxxxxxxxxxx@gmail.com>'
		subject = 'A new parcel has been delivered'
		body = ' From within a Python script / Methode : '+ d + '\n'
		msg = MIMEText(body)
		msg['From'] = fromad
		msg['To'] = toad
		msg['Subject'] = subject

		try:
			s = smtplib.SMTP('smtp.gmail.com', 587)
			s.ehlo()
			s.starttls()
			s.ehlo()
			s.login(sender, password)
			s.sendmail(sender, receivers, msg.as_string())
			"""s.login(smtpUser, smtpPass)
			s.sendmail(fromAdd, toAdd, header + '\n\n' + body)"""
			print "Successfully sent email"
			s.close() #s.quit()
		except smtplib.SMTPException:
			print "Error: unable to send email"
class WebService():
	port = 8081
	def start_server(self):
		server = HTTPServer(('', self.port), RequestHandler)
		server.serve_forever()
if __name__ == "__main__":
	webservice = WebService()
	webservice.start_server()

Code Source :

Leave a Reply

Your email address will not be published. Required fields are marked *