Friday, June 22, 2012

Empty Gmail Folder Daily using imaplib

Hi,

I don't like to see any counter or number in front of my Spam folder or the label folders which i want to be empty any point of time.

 So i thought to write a simple Python script which checks for the mails and deletes them automatically.

I am using a python module Called as IMAPLIB .

So here is the script:-


import imaplib                                                             #importing imaplib module

mail = imaplib.IMAP4_SSL('imap.gmail.com')    #creating a SSL connection to imap
mail.login('emailID', 'password')                            #Calling Login function
mail.select('[Gmail]/Spam')                                      #selecting Spam folder
result,spamuid=mail.uid('search',None,'ALL')    #Searching all mails in Spam folder
if spamuid[0]=='':
        print "Yes... No Spam"
else:
        spamUid=spamuid[0].split()                             # passing the list of UID to spamUid
        for storespamUid in spamUid:
                type,resp=mail.uid('store',storespamUid, '+FLAGS', r'(\Deleted)')
        expungeResult, response = mail.expunge() #Actual deletion of emails
        print "All Spam Mails Deleted???  ",expungeResult

closeResult,closeResponse=mail.close()


Here We have selected the Spam folder  but we can use this for any folder.
To know about all the Folders in Gmail. Just type


mail.list()

This will list all the mail folders and labels you have created on Gmail.

To Run this script daily or at anytime you want .Use CRON


Type crontab -e on Terminal

Suppose you want Cron Job everyday during working hours
This example checks the status of the database everyday (including weekends) during the working hours 9 a.m – 6 p.m

00 09-18 * * * /home/shobhit/Desktop/emptyMail.py

2 comments: