Friday, June 22, 2012

Sending Email using Python and SMTP

This is a simple python script which uses Gmail SMTP or any smtp you want to send mails using Python

First of all install module mailer :-

easy_install mailer

Here we go:-
import mailer
import traceback
        try:
                message = mailer.Message()
                message.From = "from@example.com"
                message.To = "to@example.com"
                message.Subject = "This is the Mail Title"
                message.Body = "This is the Mail body"
                mailer = mailer.Mailer('smtp.gmail.com')
                mailer.login("emailID","PASSWORD")
                mailer.use_tls=True
                mailer.send(message)
        except:
                traceback.print_exc()

This script will send mail using python and Smtp server.

 You can also send HTML mails so you have to use:-

message.HTML='''HTML DATA''' 
 

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