Archive for July, 2010

Playing With Python And Gmail

July 28th, 2010 8 comments

python In addition to its web interface Google also provides access via IMAP. The python imaplib module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060.

The IMAP4 class implements the actual IMAP4 protocol. The connection is created and protocol version (IMAP4 or IMAP4rev1) is determined when the instance is initialized.

Getting started with Python Imaplib
To start with, we will create a simple python program to login to Gmail via IMAP.

import imaplib
rc, resp = M.login('', 'pa$$word')
print rc, resp

IMAP4.IMAP4_SSL is a subclass derived from IMAP4 that connects over an SSL encrypted socket (to use this class you need a socket module that was compiled with SSL support). If host is not specified, ” (the local host) is used. If port is omitted, the standard IMAP4-over-SSL port (993) is used. keyfile and certfile are also optional – they can contain a PEM formatted private key and certificate chain file for the SSL connection.

If authentication is successful the output will be:

OK [' authenticated (Success)']

As part of our exercise we will be writing may usefull functions. It is good to create a python class file to put our functions so that at the end of our exercise we will have a cool python gmail library. Lets create a

import imaplib
class pygmail:
  def __init__(self):
    self.M = None
    self.response = None
  def login(self, username, password):
    self.M = imaplib.IMAP4_SSL(self.IMAP_SERVER, self.IMAP_PORT)
    rc, self.response = self.M.login(username, password)
    return rc
  def logout(self):
g = pygmail()
g.login('', 'pa$$word')
print g.response

Listing Mailboxes
The IMAP4.list() function list mailbox names in directory matching pattern. The directory defaults to the top-level mail folder, and pattern defaults to match anything. Returned data contains a list of LIST responses.

Add the below function to our

def get_mailboxes(self):
  rc, self.response = self.M.list()
  for item in self.response:
  return rc


for item in g.mailboxes:
  print item

This will output your Gmail mailboxes


Creating, Renaming, Deleting Mailboxes
IMAP4.create, IMAP4.rename, IMAP4.delete functions will create, rename, delete the mailboxes respectively.
Lets add three more functions to out lib.

def rename_mailbox(self, oldmailbox, newmailbox):
  rc, self.response = self.M.rename(oldmailbox, newmailbox)
  return rc
def create_mailbox(self, mailbox):
  rc, self.response = self.M.create(mailbox)
  return rc
def delete_mailbox(self, mailbox):
  rc, self.response = self.M.delete(mailbox)
  return rc

Get Mail Count
The function select a mailbox. Returned data is the count of messages in mailbox (EXISTS response). The default mailbox is ‘INBOX’. If the readonly flag is set, modifications to the mailbox are not allowed.

Add the get_mail_count function to out Python class.

  def get_mail_count(self, folder='Inbox'):
    rc, count =
    return count[0]



You can specify your mailbox also.


Get Unread Mail Count
The IMAP4.status() function request named status conditions for mailbox. The standard defines these status conditions:

MESSAGES – The number of messages in the mailbox.
RECENT – The number of messages with the Recent flag set.
UIDNEXT – The next unique identifier value of the mailbox.
UIDVALIDITY – The unique identifier validity value of the mailbox.
UNSEEN – The number of messages which do not have the Seen flag set.

Using the UNSEEN condition will return total unread messages in Inbox.

Lets define a function to get unread mail count in our

  def get_unread_count(self, folder='Inbox'):
    rc, message = self.M.status(folder, "(UNSEEN)")
    unreadCount ="UNSEEN (\d+)", message[0]).group(1)
    return unreadCount



OK, enough for a start. In the next parts of this article I will explain sending, searching, retrieving mails from Gmail via Python. So dont forget to subscribe :-)

I am pushing our small Python Gmail library to github hopefully useful to someone.

Categories: PYTHON Tags: ,

FreeBSD Get CPU & Memory Information

July 21st, 2010 No comments

beastieTo get information about CPU and Memory under FreeBSD use the following commands:

Getting CPU information:
From dmesg:

$ dmesg | grep CPU


$ grep CPU /var/run/dmesg.boot | less

Using sysctl:
CPU model:

$ sysctl hw.model

CPU clock rate:

$ sysctl hw.clockrate

No of cpus:

$ sysctl hw.ncpu

Get all information:

$ sysctl -a | grep -i cpu | less

Getting memory information:
From dmesg:

$ dmesg | grep memory


$ grep memory /var/run/dmesg.boot

Using sysctl:

$ sysctl -a | grep mem | less

FreeBSD find out memory usage

There is a Linux like free command for FreeBSD. You can get it from

$ git clone
$ cd free; make
$ sudo mv free /usr/local/bin/free
$ free -m -t


                   total          active            free        inactive            wire          cached
Memory:             1917              59            1053             575             111              41
Summary:            1917             246            1670

Freecolor is a free replacement that displays free memory graphically as a bargraph. It supports the same options as free. Install freecolor, enter:

# pkg_add -r freecolor

To see memory details, enter:

# freecolor -m


Physical  : [#######################............] 67% (162/239)
Swap      : [##################################.] 99% (599/600)
# freecolor -m -o


             total       used       free     shared    buffers     cached
Mem:           239         77        162          0          0          0
Swap:          600          0        599
Categories: FREEBSD Tags: , ,

Catch Invisible Friends On GTalk The Python Way

July 16th, 2010 4 comments

Google-TalkEver wanted to know that someone is really offline or has just gone invisible in GTalk? Here is a small trick. The bellow peace of python code get the list of invisible users from your GTalk buddy list. It uses XMPP module for python. You can install this module in Ubuntu/Debian via apt. It also requires python dns module.

$ sudo aptitude install python-xmpp python-dnspython

Now here is our script. Open your favorite text editor and save the code as ‘’. Dont forget to fill your gtalk username and password in the script.

import xmpp
# Google Talk constants
GMAIL_PASS = "secret"
if not C.connect((GTALK_SERVER,5222)):
    raise IOError('Can not connect to server.')
if not C.auth(jid.getNode(),GMAIL_PASS):
    raise IOError('Can not auth with server.')
def myPresenceHandler(con, event):
   if event.getType() == 'unavailable':
     print event.getFrom().getStripped()
C.RegisterHandler('presence', myPresenceHandler)
while C.Process(1):

Now simply run:

$ python

So , Next time do not let anyone fool you , rather catch him Invisibly .

Categories: PYTHON Tags: , , , ,