Unit – III
Chapter -6
6.1 Introduction to Python
This chapter uses Python as the primary programming language for the examples used in IoT system
design. Python is a general-purpose, high-level programming language.
● Python 2.0 was released in the year 2000 and Python 3.0 was released in the year 2008.
● Python 3.0 is not backward compatible with earlier releases.
● The most recent release referred to in this book is Python version 3.3.
● At the time of writing, there was limited library support for the 3.x versions, and operating
systems such as Linux and Mac still used Python 2.x as the default language.
● The exercises and examples in this book have been developed with Python version 2.7.
Main Characteristics of Python
Multi-paradigm programming language
Python supports more than one programming paradigm, including object-oriented programming and
structured programming.
Interpreted Language
Python is an interpreted language and does not require an explicit compilation step. The Python
interpreter executes the program source code directly, statement by statement, as a processor or scripting
engine does.
Interactive Language
Python provides an interactive mode in which the user can submit commands at the Python prompt and
interact with the interpreter directly.
Key Benefits of Python
Easy to learn, read and maintain
Python is a minimalistic language with relatively few keywords, uses English keywords, and has fewer
syntactical constructions compared to other languages. Reading Python programs is easy with pseudo-
code-like constructs. Programs written in Python are generally easy to maintain.
Object and Procedure Oriented
Python supports both procedure-oriented programming (programs written around procedures or
functions that allow reuse of code) and object-oriented programming (programs written around objects
that include both data and functionality).
Extendable
Python is an extendable language and allows integration of low-level modules written in languages such
as C/C++. This is useful when a critical portion of a program needs to be sped up.
Scalable
Due to its minimalistic nature, Python provides a manageable structure for large programs.
Portable
Since Python is an interpreted language, programmers do not have to worry about compilation, linking,
and loading of programs. Python programs can be directly executed from source code and copied from
one machine to another without worrying about portability. The Python interpreter converts the source
code to an intermediate form called byte codes and then translates this into the native language of the
specific system and runs it.
Broad Library Support
Python has broad library support and works on various platforms such as Windows, Linux, Mac, etc. A
large number of Python packages are available for various applications such as machine learning, image
processing, network programming, cryptography, etc.
6.2 Installing Python
Python is a highly portable language that works on various platforms such as Windows, Linux, Mac, etc.
Windows
● Python binaries for Windows can be downloaded from [Link]
● Python 2.7 can be directly downloaded from: [Link]
[Link]
● Once installed, the Python shell can be run at the command prompt using > python
Linux (Ubuntu)
Installing Python on Ubuntu Linux
#Install Dependencies
sudo apt-get install build-essential
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev
libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
#Download Python
wget [Link]
tar -xvf [Link]
cd Python-2.7.5
#Install Python
./configure
make
sudo make install
6.3 Python Data Types & Data Structures
6.3.1 Numbers
The number data type is used to store numeric values. Numbers are immutable data types — changing
the value of a number data type results in a newly allocated object.
Working with Numbers
#Integer
>>>a=5
>>>type(a)
<type 'int'>
#Floating Point
>>>b=2.5
>>>type(b)
<type 'float'>
#Long
>>>x=9898878787676L
>>>type(x)
<type 'long'>
#Complex
>>>y=2+5j
>>>type(y)
<type 'complex'>
>>>[Link] # 2
>>>[Link] # 5
Arithmetic Operations
#Addition: c=a+b -> 7.5 (float)
#Subtraction: d=a-b -> 2.5 (float)
#Multiplication: e=a*b -> 12.5 (float)
#Division: f=b/a -> 0.5 (float)
#Power: g=a**2 -> 25
6.3.2 Strings
A string is simply a list of characters in order. There is no limit to the number of characters a string can
hold. A string with zero characters is called an empty string.
Working with Strings
#Create string
>>>s="Hello World!"
#String concatenation
>>>t="This is sample program."
>>>r = s+t
'Hello World!This is sample program.'
#Get length of string
>>>len(s) -> 12
#Convert string to integer
>>>x="100"
>>>y=int(x) -> 100
#Formatting output
>>>print "The string (%s) has %d characters" % (s,len(s))
#Convert to upper/lower case
>>>[Link]() -> 'HELLO WORLD!'
>>>[Link]() -> 'hello world!'
#Accessing sub-strings
>>>s[0] -> 'H'
>>>s[6:] -> 'World!'
>>>s[6:-1] -> 'World'
#strip: removes leading and trailing characters
>>>[Link]("!") -> 'Hello World'
6.3.3 Lists
A list is a compound data type used to group together other values. List items need not all have the same
type. A list contains items separated by commas and enclosed within square brackets.
Working with Lists
>>>fruits=['apple','orange','banana','mango']
>>>len(fruits) -> 4
>>>fruits[1] -> 'orange'
>>>fruits[1:3] -> ['orange', 'banana']
>>>fruits[1:] -> ['orange', 'banana', 'mango']
#Appending an item
>>>[Link]('pear')
#Removing an item
>>>[Link]('mango')
#Inserting an item
>>>[Link](1,'mango')
#Combining lists
>>>eatables = fruits + vegetables
#Mixed data types in a list
>>>mixed=['data',5,100.1,8287398L]
#Individual elements can be changed
>>>mixed[0]=mixed[0]+" items"
#Lists can be nested
>>>nested=[fruits,vegetables]
6.3.4 Tuples
A tuple is a sequence data type similar to the list. A tuple consists of values separated by commas and
enclosed within parentheses. Unlike lists, the elements of tuples cannot be changed — tuples can be
thought of as read-only lists.
Working with Tuples
>>>fruits=("apple","mango","banana","pineapple")
>>>type(fruits) -> <type 'tuple'>
>>>len(fruits) -> 4
>>>fruits[0] -> 'apple'
>>>fruits[:2] -> ('apple', 'mango')
#Combining tuples
>>>eatables = fruits + vegetables
6.3.5 Dictionaries
A dictionary is a mapping data type, or a kind of hash table, that maps keys to values. Keys can be of
any data type (numbers and strings are common); values can be any data type or object.
Working with Dictionaries
>>>student={'name':'Mary','id':'8776','major':'CS'}
>>>len(student) -> 3
>>>student['name'] -> 'Mary'
>>>[Link]()
>>>[Link]()
>>>[Link]()
#A value in a dictionary can be another dictionary
>>>students={'1': student, '2':student1}
#Check if dictionary has a key
>>>student.has_key('name') -> True
>>>student.has_key('grade') -> False
6.3.6 Type Conversions
Type Conversion Examples
#Convert to string: str(10000) -> '10000'
#Convert to int: int("2013") -> 2013
#Convert to float: float("2013") -> 2013.0
#Convert to long: long("2013") -> 2013L
#Convert to list: list("aeiou") -> ['a','e','i','o','u']
#Convert to set: set(['mango','apple','banana','mango','banana'])
-> set(['mango','apple','banana'])
6.4 Control Flow
6.4.1 if
The if statement in Python is similar to the if statement in other languages.
if statement example
>>>a = 25**5
>>>if a>10000:
print "More"
else:
print "Less"
More
(If-elif-else)
6.4.2 for
The for statement in Python iterates over items of any sequence (list, string, etc.) in the order in which
they appear. This differs from the for statement in other languages such as C, in which initialization,
increment, and stopping criteria are provided.
for statement example
helloString = "Hello World"
fruits=['apple','orange','banana','mango']
#Looping over characters in a string
for c in helloString:
print c
#Looping over items in a list
i=0
for item in fruits:
print "Fruit-%d: %s" % (i,item)
i=i+1
#Looping over keys in a dictionary
for key in student:
print "%s: %s" % (key,student[key])
6.4.3 while
The while statement in Python executes the statements within the while loop as long as the while
condition is true.
while statement example — prints even numbers up to 100
>>> i = 0
>>> while i<=100:
if i%2 == 0:
print i
i = i+1
6.4.4 range
The range statement generates a list of numbers in arithmetic progression.
range examples
#Generate a list of numbers from 0 to 9
>>>range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#Generate numbers from 10 to 100 with increments of 10
>>>range(10,110,10)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
6.4.5 break / continue
The break and continue statements are similar to those in C. The break statement breaks out of the
for/while loop, whereas continue moves on to the next iteration.
break/continue examples
#Break statement example
>>>y=1
>>>for x in range(4,256,4):
y=y*x
if y > 512:
break
print y
4
32
384
#Continue statement example
>>>for item in fruits:
if item == "banana":
continue
else:
print item
6.4.6 pass
The pass statement is a null operation. It is used when a statement is required syntactically but no
command or code should execute.
pass statement example
for item in fruits:
if item == "banana":
pass
else:
print item
6.5 Functions
A function is a block of code that takes information in (as parameters), performs some computation, and
returns a new piece of information based on that parameter information. A function begins with the
keyword def, followed by the function name and parentheses containing the parameters. The code block
begins after a colon. The first statement of the function body can optionally be a documentation string
(docstring).
Function example — average grade
def averageGrade(students):
"This function computes the average grade"
sum = 0.0
for key in students:
sum = sum + students[key]['grade']
average = sum/len(students)
return average
avg = averageGrade(students)
print "The average grade is: %0.2f" % (avg)
Default Arguments
If a function with default parameter values is called with fewer parameters, or without any parameters,
the default values are used.
Default arguments example
>>>def displayFruits(fruits=['apple','orange']):
print "There are %d fruits in the list" % (len(fruits))
for item in fruits:
print item
>>>displayFruits() # uses default list
Passing by Reference
All parameters in Python functions are passed by reference. Therefore, if a parameter is changed within
a function, the change is also reflected in the calling function.
Passing by reference example
>>>def displayFruits(fruits):
print "There are %d fruits in the list" % (len(fruits))
for item in fruits:
print item
[Link]('mango')
>>>fruits = ['banana','pear','apple']
>>>displayFruits(fruits)
There are 3 fruits in the list
...
Adding one more fruit
>>>print "There are %d fruits in the list" % (len(fruits))
There are 4 fruits in the list
Keyword Arguments
Functions can also be called using keyword arguments that identify the arguments by the parameter
name. The special parameter **kwargs receives all extra keyword arguments (other than the formal
argument) as a dictionary.
Keyword arguments example
>>>def printStudentRecords(name, age=20, major='CS'):
print "Name: " + name
print "Age: " + str(age)
print "Major: " + major
>>>printStudentRecords(name='Alex')
>>>printStudentRecords(name='Bob', age=22, major='ECE')
def computer_specs(brand, **kwargs):
print(f"Computer Brand: {brand}")
print("Specifications:")
for key, value in [Link]():
print(f"{key}: {value}")
# Example usage
computer_specs(
"Dell",
RAM="16GB",
Storage="512GB SSD",
Processor="Intel i7",
Graphics="NVIDIA GTX 1650"
)
Computer Brand: Dell
Specifications:
RAM: 16GB
Storage: 512GB SSD
Processor: Intel i7
Graphics: NVIDIA GTX 1650
Variable-Length Arguments
Python functions can take variable-length arguments, passed as a tuple to the function using an argument
prefixed with an asterisk (*).
Variable-length arguments example
def student(name, *varargs):
print "Student Name: " + name
for item in varargs:
print item
>>>student('Amy', 'Age: 24')
Difference between Variable Length Argument and Keyword Argument
Feature *args **kwargs
Collects Extra positional arguments Extra keyword arguments
Data type Tuple Dictionary
Access method By index (order) By key (name)
Example call func(1, 2, 3) func(a=1, b=2, c=3)
Typical use case Flexible number of values Flexible number of named options
6.6 Modules
Python allows organizing program code into different modules, which improves code readability and
management. A module is a Python file that defines some functionality in the form of functions or
classes. Modules are imported using the import keyword; modules to be imported must be present in the
search path.
Module 'student' — [Link]
def averageGrade(students):
sum = 0.0
for key in students:
sum = sum + students[key]['grade']
average = sum/len(students)
return average
def printRecords(students):
print "There are %d students" % (len(students))
Using module student
>>>import student
>>>[Link](students)
>>>avg = [Link](students)
If only a specific function is needed, it is recommended to import only that function using the from
keyword:
Importing a specific function from a module
>>>from student import averageGrade
>>>avg = averageGrade(students)
Python comes with a number of standard modules, such as system-related modules (sys), OS-related
modules (os), mathematical modules (math, fractions, etc.), and Internet-related modules (email, json,
etc.). The built-in dir() function lists all names defined in a module.
Listing names defined in a module
>>>import email
>>>dir(email)
Feature Function Module
Definition Block of code inside a program A file containing Python code
Purpose Performs a specific task Organizes related functions & classes
Scope Exists within a program Can be imported into multiple programs
Example def add(a, b): return a+b import math
Data type Object of type function Object of type module
6.7 Packages
A Python package is a hierarchical file structure that consists of modules and sub-packages. Packages
allow better organization of modules related to a single application environment. Each directory in a
package contains a special file named __init__.py, which tells Python to treat the directory as a package;
this file may be empty or contain initialization code.
skimage package listing (example)
skimage/ Top level package
__init__.py Treat directory as a package
color/ color subpackage
__init__.py
[Link]
[Link]
rgb_colors.py
draw/ draw subpackage
__init__.py
[Link]
[Link]
exposure/ exposure subpackage
__init__.py
_adapthist.py
[Link]
feature/ feature subpackage
__init__.py
_brief.py
_daisy.py
...
For understanding:
A function is a block of code.
A module is a file containing functions/classes.
A package is a directory containing multiple modules (and possibly sub-packages).
6.8 File Handling
Python allows reading and writing to files using the file object. The open(filename, mode) function is
used to get a file object. The mode can be read (r), write (w), append (a), read and write (r+ or w+),
read-binary (rb), write-binary (wb), etc.
Reading an Entire File
>>>fp = open('[Link]','r')
>>>content = [Link]()
>>>print content
>>>[Link]()
Reading Line by Line — readline()
>>>fp = open('[Link]','r')
>>>print "Line-1: " + [Link]()
>>>print "Line-2: " + [Link]()
>>>[Link]()
Reading Lines in a Loop — readlines()
>>>fp = open('[Link]','r')
>>>lines = [Link]()
>>>for line in lines:
print line
Reading a Certain Number of Bytes — read(size)
>>>fp = open('[Link]','r')
>>>[Link](10)
'Python sup'
>>>[Link]()
Current Read Position — tell()
>>>fp = open('[Link]','r')
>>>[Link](10)
>>>currentpos = [Link]
Seeking to a Position — seek()
>>>fp = open('[Link]','r')
>>>[Link](10,0)
>>>content = [Link](10)
Writing to a File — write()
>>>fo = open('[Link]','w')
>>>content='This is an example of writing to a file in Python.'
>>>[Link](content)
>>>[Link]()
6.9 Date/Time Operations
Python provides several functions for date and time access and conversions. The datetime module
allows manipulating date and time in several ways.
Manipulating with date
>>>from datetime import date
>>>now = [Link]()
>>>print "Date: " + [Link]("%m-%d-%y")
>>>print "Day of Week: " + [Link]("%A")
>>>print "Month: " + [Link]("%B")
>>>then = date(2013, 6, 7)
>>>timediff = now - then
>>>[Link]
The time module provides various time-related functions.
Manipulating with time
>>>import time
>>>nowtime = [Link]()
>>>[Link](nowtime)
>>>[Link]([Link](nowtime))
>>>[Link]("The date is %d-%m-%y. Today is a %A. "
"It is %H hours, %M minutes and %S seconds now.")
6.10 Classes
Python is an Object-Oriented Programming (OOP) language, and provides all the standard features of
OOP such as classes, class variables, class methods, inheritance, function overloading, and operator
overloading.
Term Description
Class A representation of a type of object and a user-defined prototype for
an object composed of three things: a name, attributes, and
operations/methods.
Instance / Object An instance of the data structure defined by a class.
Inheritance The process of forming a new class from an existing (base) class.
Function overloading A form of polymorphism that allows a function to have different
meanings depending on its context.
Operator overloading A form of polymorphism that allows assignment of more than one
function to a particular operator.
Function overriding Allows a child class to provide a specific implementation of a
function already provided by the base class; the child implementation
has the same name, parameters, and return type as the base class
function.
Example of a Class
The variable studentCount is a class variable shared by all instances of the class Student and is accessed
via [Link]. The variables name, id, and grades are instance variables specific to each
instance. The special method __init__() is the class constructor, and __del__() is the class destructor.
Class example — Student
>>>class Student:
studentCount = 0
def __init__(self, name, id):
print "Constructor called"
[Link] = name
[Link] = id
[Link] = [Link] + 1
[Link]={}
def __del__(self):
print "Destructor called"
def getStudentCount(self):
return [Link]
def addGrade(self,key,value):
[Link][key]=value
def getGrade(self,key):
return [Link][key]
def printGrades(self):
for key in [Link]:
print key + ": " + [Link][key]
>>>s = Student('Steve','98928')
>>>[Link]('Math','90')
>>>[Link]('Physics','85')
>>>[Link]()
>>>mathgrade = [Link]('Math')
>>>count = [Link]()
>>>del s
Class Inheritance
In this example, Shape is the base class and Circle is the derived class. Circle inherits the attributes of
Shape and overrides the draw() method defined in Shape. It is possible to hide class attributes by naming
them with a double-underscore prefix (e.g. __label) — such attributes cannot be directly accessed via
the object; Python internally renames them by prefixing the class name (e.g. __label becomes
_Circle__label).
Class inheritance example
>>>class Shape:
def __init__(self):
print "Base class constructor"
[Link] = 'Green'
[Link] = 10.0
def draw(self):
print "Draw - to be implemented"
def setColor(self, c):
[Link] = c
def getColor(self):
return [Link]
def setLineWeight(self,lwt):
[Link] = lwt
def getLineWeight(self):
return [Link]
>>>class Circle(Shape):
def __init__(self, c, r):
print "Child class constructor"
[Link] = c
[Link] = r
[Link] = 'Green'
[Link] = 10.0
self.__label = 'Hidden circle label'
def setCenter(self,c):
[Link] = c
def getCenter(self):
return [Link]
def setRadius(self,r):
[Link] = r
def getRadius(self):
return [Link]
def draw(self):
print "Draw Circle (overridden function)"
>>>p = Point(2, 4)
>>>circ = Circle(p, 7)
>>>[Link]() -> 'Green'
>>>[Link]('Red')
>>>[Link]() -> 'Red'
>>>[Link]().getXCoordinate() -> 2
>>>[Link]() -> 'Draw Circle (overridden function)'
>>>circ.__label -> AttributeError (name-mangled)
>>>circ._Circle__label -> 'Hidden circle label'
6.11 Python Packages of Interest for IoT
6.11.1 JSON
JavaScript Object Notation (JSON) is an easy to read and write data-interchange format, used as an
alternative to XML, and is easy for machines to parse and generate. JSON is built on two structures: a
collection of name-value pairs (e.g. a Python dictionary) and ordered lists of values (e.g. a Python list).
JSON is often used for serializing and transmitting structured data over a network connection, such as
between a server and a web application.
The Python json package provides functions for encoding and decoding JSON.
Encoding & Decoding JSON in Python
>>>import json
>>>message = {
"created": "Wed Jun 31 2013",
"id":"001",
"text":"This is a test message.",
}
>>>[Link](message)
>>>decodedMsg = [Link]('{"text": "This is a test message.", "id": "001", "created": "Wed Jun 31
2013"}')
>>>decodedMsg['created']
>>>decodedMsg['text']
6.11.2 XML
XML (Extensible Markup Language) is a data format for structured document interchange. The Python
minidom library provides a minimal implementation of the Document Object Model (DOM) interface,
with an API similar to that in other languages.
# The minidom library in Python is part of the built-in [Link] package. It provides a minimal
implementation of the Document Object Model (DOM) — a tree-based way to represent and
manipulate XML documents.
Parsing an XML file in Python
from [Link] import parse
dom = parse("[Link]") # parse() reads the XML file and builds a DOM tree — a hierarchical structure of
elements, attributes, and text nodes.
for node in [Link]('plant'): # getElementsByTagName('plant') finds all
<plant> tags.
id=[Link]('id') # getAttribute('id') retrieves the value of the id attribute.
print "Plant ID:", id
common=[Link]('common')[0].childNodes[0].nodeValue #
getElementsByTagName('common')[0] gets the first <common> tag inside <plant> ,
.childNodes[0].nodeValue retrieves the text inside that tag.
print "Common:", common
botanical=[Link]('botanical')[0].childNodes[0].nodeValue
print "Botanical:", botanical
zone=[Link]('zone')[0].childNodes[0].nodeValue
print "Zone:", zone
You repeat this for <botanical> and <zone> tags.
Result: You print each plant’s ID, common name, botanical name, and zone.
Content for XML File looks like
<CATALOG>
<PLANT id="001">
<COMMON>Bloodroot</COMMON>
<BOTANICAL>Sanguinaria canadensis</BOTANICAL>
<ZONE>4</ZONE>
</PLANT>
<PLANT id="002">
<COMMON>Columbine</COMMON>
<BOTANICAL>Aquilegia canadensis</BOTANICAL>
<ZONE>3</ZONE>
</PLANT>
<PLANT id="003">
<COMMON>Marsh Marigold</COMMON>
<BOTANICAL>Caltha palustris</BOTANICAL>
<ZONE>4</ZONE>
</PLANT>
</CATALOG>
Creating an XML file with Python
from [Link] import Document
doc = Document()# Create a new DOM document
# create base element
base = [Link]('Class') # <Class> becomes the root element of your XML.
[Link](base)
# create an entry element
entry = [Link]('Student') # Adds <Student> inside <Class>.
[Link](entry)
# create Name element and append to entry
name = [Link]('Name') # Creates <Name>Alex</Name> inside <Student>.
nameContent = [Link]('Alex')
[Link](nameContent)
[Link](name)
# create Major element and append to entry
major = [Link]('Major') #Creates <Major>Alex</Major> inside <Student>.
majorContent = [Link]('ECE')
[Link](majorContent)
[Link](major)
#Save the file
fp = open('[Link]','w') #Writes the XML structure to [Link]
[Link]()
[Link]()
Result:
<Class>
<Student>
<Name>Alex</Name>
<Major>ECE</Major>
</Student>
</Class>
Concept Description
DOM (Document Object Model) Represents XML as a tree of nodes (elements, attributes, text).
Element A tag like <Student> or <Name>.
Attribute A property inside a tag, e.g., <plant id="001">.
Text Node The actual text inside an element.
Parsing Reading and interpreting XML into a DOM tree.
Serialization Writing a DOM tree back into XML format.
6.11.3 HTTPLib & URLLib
HTTPLib2 and URLLib2 are Python libraries used in network/Internet programming. HTTPLib2 is an
HTTP client library, and URLLib2 is a library for fetching URLs.
HTTP GET request example using HTTPLib
>>> import httplib2
>>> h = [Link]()
>>> resp, content = [Link]("[Link] "GET")
[Link]() sends an HTTP request to the given URL ([Link] using the method "GET".
It returns two values:
resp → A dictionary-like object containing response headers and status code (e.g., 200 OK,
content type, etc.).
content → The actual body of the response (HTML, JSON, XML, etc.).
A request object is created by calling [Link] with the URL to fetch as input parameter. Then
[Link] is called with the request object, which returns the response object for the requested
URL. The response object is read by calling the read() function.
HTTP request example using URLLib2
>>> import urllib2
>>> req = [Link]('[Link]
>>> response = [Link](req)
>>> response_page = [Link]()
An HTTP POST request example — the data in the POST body is encoded using the urlencode function
from urllib.
HTTP POST example using HTTPLib2
>>> import httplib2
>>> import urllib
>>> h = [Link]()
>>> data = {'title': 'Cloud computing'}
>>> resp, content = [Link]("[Link]
"POST", [Link](data))
Sending data (e.g. an HTML form submission) to a URL using URLLib2 is similar to the HTTPLib2
POST example, but uses a URLLib2 request object instead.
Sending data to a URL using URLLib2
>>> import urllib
>>> import urllib2
>>> url = '[Link]
>>> values = {'title':'Cloud Computing', 'language':'Python'}
>>> data = [Link](values)
>>> req = [Link](url, data)
>>> response = [Link](req)
>>> the_page = [Link]()
6.11.4 SMTPLib
Simple Mail Transfer Protocol (SMTP) is a protocol that handles sending email and routing email
between mail servers. The Python smtplib module provides an SMTP client session object that can be
used to send email.
To send an email: first a connection is established with the SMTP server by calling [Link] with
the server name and port. The username and password are then used to log in to the server. The email is
sent by calling [Link] with the from address, the list of to-addresses, and the message.
Sending email in Python (from a Gmail account)
import smtplib
from_email = '<enter-gmail-address>'
recipients_list = ['<enter-sender-email>']
cc_list = []
subject = 'Hello'
message = 'This is a test message.'
username = '<enter-gmail-username>'
password = '<enter-gmail-password>'
server = '[Link]'
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message, login, password, smtpserver):
header = 'From: %s\n' % from_addr
header += 'To: %s\n' % ','.join(to_addr_list)
header += 'Cc: %s\n' % ','.join(cc_addr_list)
header += 'Subject: %s\n\n' % subject
message = header + message
server = [Link](smtpserver)
[Link]()
[Link](login,password)
problems = [Link](from_addr, to_addr_list, message)
[Link]()
#Send email
sendemail(from_email, recipients_list, cc_list, subject,
message, username, password, server)