CyberKeeda In Social Media
Showing posts with label Python-Cheats. Show all posts
Showing posts with label Python-Cheats. Show all posts

Python - Send HTML Table as email body.



SMTPLIB

A python base package to send emails.


Within this post, we will cover.

  • How to use prettytable library to create tabular data in console.
  • How to convert prettytable tabular data output in HTML format
  • How we can send HTML email using Python.
  • How can we integrate mime with email.
  • Code snippet to send HTML email along with Texr
  • How to send email as MultiPart message content ( Text + HTML) 

We will start with the use case:

  • I have a html table and and a Link that must be within the same email body and not as an attachment.
  • So for now, i am using PreetyTable to provide output of my table in HTML format.

 

Intended Table.


FirstnameLastnameAge
JillSmith50
EveJackson94
JohnDoe80


How to create Tabular data in CLI using prettytable.


mytable.py
from prettytable import PrettyTable
    
tabular_fields = ["Firstname", "Lastname", "Age"]
tabular_table = PrettyTable()
tabular_table.field_names = tabular_fields 
tabular_table.add_row(["Jill","Smith", 50])
tabular_table.add_row(["Eve","Jackson", 94])
tabular_table.add_row(["John", "Doe", 80])

>>> print(tabular_table)
+-----------+----------+-----+
| Firstname | Lastname | Age |
+-----------+----------+-----+
|    Jill   |  Smith   |  50 |
|    Eve    | Jackson  |  94 |
|    John   |   Doe    |  80 |
+-----------+----------+-----+

To print the data as an HTML output use the below code snippet


mytable.py
from prettytable import PrettyTable
    
tabular_fields = ["Firstname", "Lastname", "Age"]
tabular_table = PrettyTable()
tabular_table.field_names = tabular_fields 
tabular_table.add_row(["Jill","Smith", 50])
tabular_table.add_row(["Eve","Jackson", 94])
tabular_table.add_row(["John", "Doe", 80])

>>> print(tabular_table.get_html_string())

<table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
    </tr>
</table>
Now as we already know how to create html output for a specific table using prettytable, we will use the same html output within our email body.


  • Here is the code.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def trigger_email():
    my_message = tabular_table.get_html_string()
    text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"

    html = """\
    <html>
        <head>
        <style>
            table, th, td {
                border: 1px solid black;
                border-collapse: collapse;
            }
            th, td {
                padding: 5px;
                text-align: left;    
            }    
        </style>
        </head>
    <body>
    <p>Customer Inventory!<br>
       Here are the details?<br>
       Link to register. <a href="http://www.python.org">link</a> you wanted.<br>
       %s
    </p>
    </body>
    </html>
    """ % (my_message)

    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    sendFrom = 'Purchase Update <admin@cyberkeeda.com>'
    sendTo = 'customer@cyberkeeda.com'
    # Create the root message and fill in the from, to, and subject headers
    msg = MIMEMultipart('alternative')
    msg['Subject'] = 'Purchase details Status'
    msg['From'] = strFrom
    msg['To'] = strTo
    msg.attach(part1)
    msg.attach(part2)
    
    smtp = smtplib.SMTP('smtp.cyberkeeda.com')
    smtp.sendmail(strFrom, strTo, msg.as_string())
    smtp.quit()
So modify the above with your requirement.



Read more ...

Python : Selenium and Chromedriver to take webpage screenshot and send it via email.




Browser Automation using Python


Within this post, we will cover.

  • Use of selenium and chromedriver to take screenshot of most recent webpage status.
  • Will leverage the basic preinstalled libraries to send email.
  • Will know, how we can send an image as a part of email body not as an attachment.
  • Will use the headless mode option of chromdriver, that's is the entire operation will run in background no GUI chrome events will be observed.

We will start with the use case:

  • if you have a requirement to check the current status of a webpage multiple times within a day/hour.
  • If you have multiple of webpages to look into periodically without opening any of it, check status of directly from your inbox only.
We will use a python script here and perform the below operations sequentially.
  1. Take screenshot of webpage using Python selenium library and google chrome webdriver and save it in our folder by name screenshot.png
  2. Use Python base library email and use it's multipart function to draft image as an email body.
  3. Use Python base library to send email using SMTP server.
Steps:
  • Download mandatory requirements.
    • Install selenium library from PIP
C:\Users\cyberkeeda> pip install selenium
First confirm which chrome browser you have on your system, for this open Chrome Browser --> Click on 3 dots at the top right corner of chrome --> Help
--> About Chrome Chrome --> You will get google chrome version.
  • Create an new directory and place your above chrome webdriver into it.
  • Note your organizations SMTP server URL/IP.
  • Create a new Python file and paste the below script lines within it.
  • Paste and save your python script and replace the below lines with yours.
    • driverPath  : Replace it with the path you have kept your downloaded chromedriver 
    • chrome_options.add_argument('window-size=1920,1080')  : Replace it with resolution what you want for the screenshot.
      • 720p = 1280 x 720 - is usually known as HD or "HD Ready" resolution
      • 1080p = 1920 x 1080 - is usually known as FHD or "Full HD" resolution
      • 1440p = 2560 x 1440 - is commonly known as QHD or Quad HD resolution
    • driver.get('https://www.mohfw.gov.in/'): Replace it your URL.
    • sendFrom : Replace it your sender's email address.
    • sentTo: Replace it your recipient email address. ( You can use same email for sendFrom and sendTo)
    • smtp = smtplib.SMTP('smtp.cyberkeeda.com') : Replace it your own smtp server or IP.


import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from time import sleep

def grab_screenshot():

    # Path for your downloaded chromedriver.
    driverPath = '\\Users\\cyberkeeda\\BrowserAutomation\\chromedriver'

    # To activate GUI Mode Uncomment te below two lines
    # And comment the below four lines staring from chrome_options to driver

    #driver = webdriver.Chrome(executable_path=driverPath)
    #driver = webdriver.Chrome(driverPath)
    
    chrome_options = Options()
    chrome_options.add_argument("headless")
    chrome_options.add_argument("--start-maximized")
    chrome_options.add_argument('window-size=1920,1080')
    driver = webdriver.Chrome(options=chrome_options, executable_path=driverPath)

    driver.get('https://www.mohfw.gov.in/')
    sleep(15)
    driver.get_screenshot_as_file("screenshot.png")
    driver.close()
    driver.quit()

def emailScreenShot():

    grab_screenshot()

    html_string = """ 
                    '<b>Covid-19 Cases </b> <br> 
                    Do and Don't Link :https://www.mohfw.gov.in/pdf/socialdistancingEnglish.pdf <br>
                    <img src="cid:image1"><br>Regards <br> Automation
                  """

    sendFrom = 'Covid Update <dontreply-covid@cyberkeeda.com>'
    sendTo = 'admin@cyberkeeda.com'
    # Create the root message and fill in the from, to, and subject headers
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'Covid-19 Cases Status'
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText('This is the alternative plain text message.')
    msgAlternative.attach(msgText)

    # We reference the image in the IMG SRC attribute by the ID we give it below
    msgText = MIMEText(html_string, 'html')
    msgAlternative.attach(msgText)

    # This example assumes the image is in the current directory
    fp = open('screenshot.png''rb')
    msgImage = MIMEImage(fp.read())
    fp.close()

    # Define the image's ID as referenced above
    msgImage.add_header('Content-ID''<image1>')
    msgRoot.attach(msgImage)

    # Send the email (this example assumes SMTP authentication is required)
    try:
        smtp = smtplib.SMTP('smtp.cyberkeeda.com')
        smtp.sendmail(sendFrom, sendTo, msgRoot.as_string())
        smtp.quit()
    except:
        print("SMTP Error")

emailScreenShot()



Hope this blog post helps you to meet your requirement, in case of any support using above script do comment.
 

Read more ...

Python : How to extract desired cell values from a table created by module PrettyTable


PrettyTable

It is simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables. It was inspired by the ASCII tables used in the PostgreSQL shell psql. PrettyTable allows for selection of which columns are to be printed, independent alignment of columns (left or right justified or centred) and printing of “sub-tables” by specifying a row range.

Official Document : Link

There could be many uses cases while using it, here in this blog post we will cover how we can extract our desired cell values from preetyTable.

So we will start by 
  • Importing module
  • Creating object
  • Add Feilds
  • Add Data
from prettytable import PrettyTable           # importing module

tabular_table = PrettyTable()                 # creating object
tabular_fields = ["Name""Age""Gender"]    # Define Field List

tabular_table.field_names = tabular_fields    # Add Fields to table

tabular_table.add_row(["Tokyo""33""M"])   # Add Data
tabular_table.add_row(["Narobi""74""M"])
tabular_table.add_row(["Denver""21""F"])

print(tabular_table)

Output.
+--------+-----+--------+
|  Name  | Age | Gender |
+--------+-----+--------+
| Tokyo  |  33 |   M    |
| Narobi |  74 |   M    |
| Denver |  21 |   F    |
+--------+-----+--------+


Use Case 1.

  • Extract cell values for a specific field only from prettyTable
Below For loop will help to do so.


for row in tabular_table:
     print (row.get_string(fields=["Name"]))


Output.
+-------+
|  Name |
+-------+
| Tokyo |
+-------+
+--------+
|  Name  |
+--------+
| Narobi |
+--------+
+--------+
|  Name  |
+--------+
| Denver |
+--------+


Use Case 2.

  • Extract cell values without header or border from prettyTable

for row in tabular_table:
     row.border = False
     row.header = False
     print (row.get_string(fields=["Name"]).strip())

Output.
Tokyo
Narobi
Denver
Read more ...

How to make your Python Django App Reusable


Django is cool and it's features like any other python libraries and frameworks are way more cooler then it.

One of the best feature is to make your django app easily distributable for re usability.

Within this blog post, we will cover.
  • How can we build a django app a python package as xyz.tar.gz
  • How can be uploaded our created django app python package to Python Package Index, simple know as PyPI.
  • How we can Install our created package locally via tar.gz file.
  • How can we install using standard pip command as "pip install your_py_package"
Assumptions.
  • We assume you already have a running Django Project and beneath it there must be an application, which you want to package and make it disributable.
  • Here in this blog post we already have a Django project named as docdocGo and within it we have created a django application named as FilesNow, we will cover all things taking it an example.
  • FilesNow is an django application, that can be used to download contents from a AWS S3 bucket within it's temporary directory and serve it as a presentable media to view or download for a user, it deletes the files after a fix set interval. 
  • FilesNow on GitHub linkhttps://github.com/Jackuna/django-filesnow
Here is how our django project and it's  directory look like.

Dependencies

  • Python 3+
  • Django 2.2+
  • PIP
  • Twine ( pip install twin )

Lets proceed and how to Package our filesnow django app.
  1. Create a new empty directory outside our django project and name it something relevant to your app, here we will use it name as django-filesnow.
  2. Copy the entire application directory and paste under newly created directory.
  3. Toggle to directory django-filesnow and lets move ahead and create few required files within it.
  • Create a file django-filesnow/README.rst with the below content and do replace with your own.
Content of django-filesnow/README.rst
=========
FilesNow
=========

FilesNow is a Django app to download documnets, images 
from AWS S3 and serve is a temporary static content to customers.

FilesNow is a way to serve AWS S3 documents/media files
without giving access to your s3 buckets.

FilesNow itself cleans it's downloaded presentable
files, as such maintainig a healthy file system

Dependecies
-----------
AWS Boto3 Framework : pip install boto3
Configure AWS Credentilas using command : aws configure

Quick start
-----------

1. Add "filesnow" to your INSTALLED_APPS setting like this::

    INSTALLED_APPS = [
        ...
        'filesnow',
    ]

2. Include the polls URLconf in your project urls.py like this::

    path('filesnow/', include('filesnow.urls'))

 
3. Start the development server ``python manage.py runserver 0.0.0.0:9090``

4. Visit http://127.0.0.1:9090/filesnow and explore it.
  • Create a license file django-filesnow/LICENSE , choose license as per requirement of yours ( GNU, BSD, MIT ) etc, Choose a license website ( https://choosealicense.com/ ) can help you to guide about your required license and it's content. I have used MIT license and you can find it's content within my Github repo.
  • Create two setup files within same directory and name it as django-filesnow/setup.cfg   and django-filesnow/setup.py with the below content and do replace with your own.
Content of django-filesnow/setup.cfg
[metadata]
name = django-filesnow
version = 0.1
description = A Django app to download cloud contents.
long_description = file: README.rst
url = https://github.com/Jackuna/django-filesnow
author = Jackuna
author_email = admin@cyberkeeda.com
license = MIT License
classifiers =
    Environment :: Web Environment
    Framework :: Django
 Framework :: Django :: 2.2
    Intended Audience :: Developers
    License :: OSI Approved :: MIT License
    Operating System :: OS Independent
    Programming Language :: Python
    Programming Language :: Python :: 3
    Programming Language :: Python :: 3 :: Only
    Programming Language :: Python :: 3.6
    Programming Language :: Python :: 3.7
    Programming Language :: Python :: 3.8
    Topic :: Internet :: WWW/HTTP
    Topic :: Internet :: WWW/HTTP :: Dynamic Content

[options]
include_package_data = true
packages = find:
Content of django-filesnow/setup.py
from setuptools import setup

setup()
  • Only Python modules and packages are included in the package by default. To include additional files, we’ll need to create a MANIFEST.in file.  To include the templates, the README.rst and our LICENSE file, create a file django-polls/MANIFEST.in with the following contents:
Content of django-filesnow/MANIFEST.in
include LICENSE
include README.rst
recursive-include filesnow/static *
recursive-include filesnow/templates *
So now we are all done with creation of required files in order to package your app, lets toggle again into the parent directory ( django-filesnow )and open a terminal/command prompt and run the below command to build our package.
# python setup.py sdist
Once command ends with successfully, and additional directory with name "dist" will be created, it contains our bundled and packaged django app, in our case  django-filesnow-0.1.tar.gz has been created.

Thus we have packaged our django app by name django-filesnow-0.1.tar.gz, we can distribute it as per your requirement, like uploading to repositories like github, email, uploading to any forum or website.

Let's know how to install our packaged filesnow django app django-filesnow-0.1.tar.gz, use the below command to install it.
# python -m pip install --user django-polls-0.1.tar.gz
Within Above command will install it, for windows we can located the installed application by name "filesnow" under directory.

"C:\Users\Jackuna\AppData\Roaming\Python\Python37\site-packages\filesnow"

Please note:
Above highlighted in red may varry, depending upon your system and package.
Package will be installed by name filesnow only not django-filesnow.
Within next post, we will know the remaining topics !

Read more ...

Python : Print() examples with parameters

Print

Nothing more is required to explain what does the print function does, it's name is itself self explanatory.
Print function is used to display /print messages into the screen.

Within python we can use ether pair of single inverted commas '  ' or double inverted "  "  within single brackets (  )  both gives the same result.

>>> print  ('Hello World')

Hello World

Print() with Parameters.

I'm adding some of the print function usage along with various parameters.

Print() with Sep

SEP commonly a short form of separator,  Separator between the arguments to print() function in Python is space by default (softspace feature) , which can be modified and can be made to any character, integer or string as per our choice.

Default behaviour of python with softspace.

>>> print('A','B','C')
A B C

#Trick to disable softspace using sep parameter
>>> print('A','B','C',sep='')
ABC

One more example.

>>> print('13','11','2018')
13 11 2018

#Trick to format a date
>>> print('13','11','2018', sep='-')
13-11-2018

Print() with End

End parameter along with print can be used to align data into a same single line along with required character,symbol or word.
Example:

>>> print('Welcome')
>>> print('to')
>>> print('cyberkeeda.com')

Output:
Welcome
 to
Cyberkeeda.com
Now, with help of end parameter, we can allign all these three different lines by one, along with extra characters too

>>> print('Welcome', end '  ')
>>> print('to', end '  ')
>>> print('cyberkeeda.com', end ' ! ')
Output:
Welcome to Cyberkeeda.com !

One more example ( SEP with END )
>>> print(10,20,30,sep=':', end='...')
>>> print(60,70,80,sep='-')

Output:
10:20:30...60-70-80

Print Formatted strings and Variables on the same line.

Before knowing anything, please note the below abbreviations.

%i==>  int
%d==> int
%f==>  float
%s==>  str

print("formatted String" %(variable list))

Examples.

>>> print("value is :%d" %(12))
value is  : 12

>>> print("My name is :%s and age is :%d" %('Cyberkeeda',23))
My name is : Cberkeeda and age is  : 23


Read more ...
Designed By Jackuna