Monday 16 June 2014

Send email with Outlook in Python

We can send email by outlook with filling all details by python code. and we can implement send email functionality in our project easily.

First we have to give details like from, to  subject and attachment then this all details will be filled in outlook with python code. please see the below code.


import win32com.client
from win32com.client import Dispatch, constants
 
const=win32com.client.constants
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "I AM SUBJECT!!"
newMail.Body = "I AM IN THE BODY\nSO AM I!!!"
newMail.To = "abc@abc.com"
attachment1 = r"E:\test\logo.png"

newMail.Attachments.Add(Source=attachment1)
newMail.display()

#newMail.send()

How to send email with attachments in python

Send email functionality is very useful functionality. for this we have to configured server configuration as your web email configuration.

If you have gmail email SMTP configuration then you have to configured as below with Send email functionality.


                
                import smtplib, os
                from email.mime.text import MIMEText
                from email.mime.multipart import MIMEMultipart
                from email.mime.base import MIMEBase
                from email import Encoders
 
                gmail_user = "ashish@example.com"
                gmail_name = "Ashish "
                gmail_pwd = "example@123"
                name='Ashish'
                attach='E:/test/test.pdf'
                body ="Dear %s ,\n\nPlease find the attached files.\n\nThanks and Regards:\nAshish" % (name)
                msg = MIMEMultipart()
                msg['From'] = gmail_name
                msg['To'] = "ashish1@example.com"
                msg['Subject'] = "Send email with attachment"
                msg.attach(MIMEText(body))
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(attach))
                msg.attach(part)
                mailServer = smtplib.SMTP("smtp.gmail.com", 25)
                mailServer.ehlo()
                mailServer.starttls()
                mailServer.ehlo()
                mailServer.login(gmail_user, gmail_pwd)
                mailServer.sendmail(gmail_name, "ashish1@example.com", msg.as_string())   # name + e-mail address in the From: field
                mailServer.close()

Sunday 15 June 2014

Read zip files in python


We can read all the files without extracting zip file easily. and we can read line by line in zip files.

Script
try:
   root = zipfile.ZipFile("C:\Python27\Project\Rokar.zip", "r")
except:
   root = "." 
data=[]
for name in root.namelist()

       for line in root.read(name):
           data.append(line)
print ''.join(data)


or
try:
   root = zipfile.ZipFile("C:\Python27\Project\Rokar.zip", "r")
except:
   root = "."  

with root as z:

   with z.open('manage.py') as f:

       for line in f:

           print line

Saturday 14 June 2014

Find MAC address of system in python



Simple we can find mac addresses by socket connection and netifaces library. first you have to download this library from given below link according to python version and OS .

https://pypi.python.org/pypi/netifaces#downloads



from socket import *
import netifaces as nif
def mac_for_ip(ip):
    'Returns a list of MACs for interfaces that have given IP, returns
None if not found'
    for i in nif.interfaces():
        addrs = nif.ifaddresses(i)
        try:
            if_mac = addrs[nif.AF_LINK][0]['addr']
            if_ip = addrs[nif.AF_INET][0]['addr']
        except IndexError, KeyError: #ignore ifaces that dont have MAC or IP
            if_mac = if_ip = None
        if if_ip == ip:
            return if_mac
    return None

print mac_for_ip(gethostbyname_ex(gethostname())[2][0])

 
Output : 1e:23:3j:49:8b

Thursday 12 June 2014

How to encrypt and decrypt data in python



  • Encryption and decryption is standard, well-known algorithms for data secure.
  • The established, efficient pycrypto library provides the algorithm implementations (the cipher used is AES256).
  • It includes a check (an HMAC with SHA256) to warn when ciphertext data are modified.
  • It tries to make things as secure as possible when poor quality passwords are used (PBKDF2 with SHA256, a 256 bit random salt (increased from 128 bits in release 3.0.0), and 10,000 rounds). But that doesn't mean you should use a poor password!.
  • Using a library, rather than writing your own code, means that we have less solutions to the same problem. That means more chance of finding bugs, which means more reliable, more secure code.

How to encrypt data


Step 1: Download the Crypto package from here and install it in your system.

For windows: 
        pycrypto-2.3.win32-py2.7.exe [545 Kb] [Python 2.7] [32 bit] 
        pycrypto-2.3.win-amd64-py2.7.exe [572 Kb] [Python 2.7] [64 bit]
 
For Linux or Mac and other OS: 
        https://www.dlitz.net/software/pycrypto/


Step 2: Keep pkcs7.py file in your root directory.



Step 3: First you have to define a self-created 16 digit key( key and IV will be 16 digit, 32,64…) which you know, only that key will decrypt data otherwise it will not decrypt. Here I am doing encoding by PKCS7 then encryption by crypto and again encoded by base64. 

from Crypto.Cipher import AES
from pkcs7 import PKCS7Encoder
import pkcs7,threading, base64


text=’my secret data’
key = 'secret#456!23key'
iv = 'Key@123Key@123fd'
aes = AES.new(key, AES.MODE_CBC, iv)
encoder = PKCS7Encoder()
pad_text = encoder.encode(text)
cipher = aes.encrypt(pad_text)
enc_cipher = base64.b64encode(cipher)
print enc_cipher



Output is 


CdGubxMcUT1vM0p1XkNscw==

How to decrypt data


For decryption we have to follow apposite procedure means 1st  we have to decode by base64 , decrypt by Crypto and then decode by PKCS7.

decodetext =  base64.b64decode(enc_cipher)
aes = AES.new(key, AES.MODE_CBC, iv)
cipher = aes.decrypt(decodetext)
pad_text = encoder.decode(cipher)
print pad_text


Output is
 

my secret data



Crypto cypher encryption is very secure.