Skip to content

Instantly share code, notes, and snippets.

@jmjeong
Created November 17, 2009 11:05
Show Gist options
  • Save jmjeong/236838 to your computer and use it in GitHub Desktop.
Save jmjeong/236838 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# purgegmail.py
#
# Google mail purge utility
# - delete all mail before purgeDate(datetime.date(2007,11,06))
#
# [2009-11-17 Tue] Jaemok Jeong(jmjeong@gmail.com)
#
# ChangeLog:
# - On gmail, delete flag does not work.
# To delete mail, article should be copied to [Gmail]/Trash
# - If verbose is off, act 'bulk copy'
#
import imaplib, email, rfc822
import datetime, time
import email.header
import getpass
import sys
# add user information
gmail_user = '' # gmail nemustech 계정(jmjeong@nemustech.co.kr)
gmail_pass = '' # gmail nemustech 암호
purgeDate = datetime.date(2007,01,8) # 이 날짜 앞의 메일들은 전부 삭제
verbose = False
# constant
gmail_host = 'imap.gmail.com'
def decodeHeaderStr(stringList):
resultStr = ""
for item in stringList:
try:
if item[1] == None:
# encoding이 없으면 euc-kr로 간주?
resultStr += unicode(item[0], 'euc-kr').encode('utf-8')
else:
resultStr += unicode(item[0], item[1]).encode('utf-8')
except:
pass
return resultStr
def process():
imap = imaplib.IMAP4_SSL(gmail_host)
try:
imap.login(gmail_user, gmail_pass)
except:
print "Login failed"
sys.exit(-1)
num = imap.select()
searchString = ('(before "%s")' % purgeDate.strftime("%d-%b-%Y"))
typ, data = imap.search (None, searchString)
y_or_n = raw_input("Delete %d messages? " % len(data[0].split(' ')))
if (not (y_or_n == 'y' or y_or_n == 'Y')): return
if verbose:
for num in data[0].split():
typ, data = imap.fetch(num, '(BODY[HEADER.FIELDS (FROM SUBJECT DATE)])')
emailBody = data[0][1]
mail = email.message_from_string(emailBody)
# print "--"
# print ':' + mail['Subject'] + ':'
# print ':' + mail['From'] + ':'
# print ':' + mail['Date'] + ':'
# print "--"
try:
subjectStr = email.header.decode_header(mail['Subject'])
fromStr = email.header.decode_header(mail['From'].replace('"', ''))
date = datetime.date.fromtimestamp(time.mktime(rfc822.parsedate(mail['Date'])))
except email.header.HeaderParseError:
print "error"
pass
print "Deleted : " + decodeHeaderStr(subjectStr) + ":::" \
+ decodeHeaderStr(fromStr) + ":::" + date.strftime("%m-%d-%y")
typ, data = imap.copy(num, '[Gmail]/Trash')
if typ != "OK":
print "Delete failed!"
else:
data = ','.join(data[0].split(' '))
typ, data = imap.copy(data, '[Gmail]/Trash')
if typ == "OK":
print "Delete sucessful!"
else:
print "Delete failed!"
imap.close()
imap.logout()
if __name__ == '__main__':
if gmail_user == '':
gmail_user = raw_input('id: ')
if gmail_pass == '':
gmail_pass = getpass.getpass()
process()
print "Finished..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment