How to delete messages from Gmail using python IMAPclient ?

Google does not delete all messages at once according to http://support.google.com/mail/answer/78755?hl=en.
So, first, you have to delete messages in each folder:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from imapclient import IMAPClient

client = IMAPClient('imap.googlemail.com', use_uid=True, ssl=True)
client.login('mymailbox@gmail.com', 'password')

folders = [
    'INBOX',
    '[Gmail]/Drafts',
    '[Gmail]/Important',
    '[Gmail]/Sent Mail',
    '[Gmail]/Spam',
    '[Gmail]/Starred',
]

for f in folders:
    fold = client.select_folder(f)
    res = client.delete_messages(client.search())
    res = client.expunge()
    client.close_folder()

#Google automatically will move deleted messages to "All Mail" folder. 
#Now we can remove all messages from "All Mail"

client.select_folder("[Gmail]/All Mail")
client.set_gmail_labels(client.search(), '\\Trash')
client.delete_messages(client.search())
client.expunge() 
client.logout()

More information on how to work with Gmail using python IMAPClient can be found directly at http://imapclient.freshfoo.com/browser/imapclient/livetest.py
Read the source code, Luke 🙂

Simple site pinger

This simple script pings your websites and notifies when a website is down.
It’s written in python >= 2.5 and might be usefull for administrators and programmers.
Some parts of it was found somewhere in the internet and adjusted a bit for my needs.

Required packages can be installed easily from repository ( Ubuntu example ):

sudo apt-get install python-notify

or using pip/easy_install as well

sudo pip install notify

Running this script from command line is a bit annoying so I put to run it by crontab each 30 min:

$ crontab -e
*/30 * * * * DISPLAY=:0 /usr/bin/python /home/vs/bin/pingwebsites.py

Note that you need to set DISPLAY option to make notification visible for current X session.

#!/usr/bin/env python
from threading import Thread
import subprocess
from Queue import Queue
from pynotify import *

num_threads = 4
queue = Queue()
hosts = [
    ,"mysite.com"
    ,"myanothersite.com"
]
#wraps system ping command
def pinger(i, q):
    """Pings subnet"""
    while True:
        host = q.get()
        #print "Thread %s: Pinging %s" % (i, host)
        ret = subprocess.call("ping -c 5 %s" % host,
                        shell=True,
                        stdout=open('/dev/null', 'w'),
                        stderr=subprocess.STDOUT)
        if ret == 0:
            pass
            #print "%s: is alive" % host
        else:
            init("Server checker")
            msg =  "%s: did not respond" % host
            Notification("Server checker", msg).show()
        q.task_done()
#Spawn thread pool
for i in range(num_threads):

    worker = Thread(target=pinger, args=(i, queue))
    worker.setDaemon(True)
    worker.start()
#Place work in queue
for host in hosts:
    queue.put(host)
#Wait until worker threads are done to exit
queue.join()