Created
November 17, 2009 07:46
-
-
Save jmjeong/236756 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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([email protected]) | |
# | |
import imaplib, email, rfc822 | |
import datetime, time | |
import email.header | |
import getpass | |
import sys | |
# add user information | |
gmail_user = '' # gmail nemustech 계정([email protected]) | |
gmail_pass = '' # gmail nemustech 암호 | |
purgeDate = datetime.date(2008,05,06) # 이 날짜 앞의 메일들은 전부 삭제 | |
verbose = True | |
# 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")) | |
type, 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 | |
for num in data[0].split(): | |
imap.store(num, '+FLAGS', '\\Deleted') | |
if verbose: | |
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") | |
imap.expunge() # permanently remove deleted items | |
imap.close() | |
imap.logout() | |
if __name__ == '__main__': | |
if gmail_user == '': | |
gmail_user = raw_input('id: ') | |
if gmail_pass == '': | |
gmail_pass = getpass.getpass() | |
process() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment