Guest User

Untitled

a guest
Apr 24th, 2018
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # purgegmail.py
  5. #
  6. # Google mail purge utility
  7. # - delete all mail before purgeDate(datetime.date(2007,11,06))
  8. #
  9. # [2009-11-17 Tue] Jaemok Jeong(jmjeong@gmail.com)
  10. #
  11.  
  12. import imaplib, email, rfc822
  13. import datetime, time
  14. import email.header
  15. import getpass
  16. import sys
  17.  
  18. # add user information
  19. gmail_user = '' # gmail nemustech 계정(jmjeong@nemustech.co.kr)
  20. gmail_pass = '' # gmail nemustech 암호
  21. purgeDate = datetime.date(2008,05,06) # 이 날짜 앞의 메일들은 전부 삭제
  22. verbose = True
  23.  
  24. # constant
  25. gmail_host = 'imap.gmail.com'
  26.  
  27. def decodeHeaderStr(stringList):
  28. resultStr = ""
  29. for item in stringList:
  30. try:
  31. if item[1] == None:
  32. # encoding이 없으면 euc-kr로 간주?
  33. resultStr += unicode(item[0], 'euc-kr').encode('utf-8')
  34. else:
  35. resultStr += unicode(item[0], item[1]).encode('utf-8')
  36. except:
  37. pass
  38.  
  39. return resultStr
  40.  
  41. def process():
  42.  
  43. imap = imaplib.IMAP4_SSL(gmail_host)
  44.  
  45. try:
  46. imap.login(gmail_user, gmail_pass)
  47. except:
  48. print "Login failed"
  49. sys.exit(-1)
  50.  
  51. num = imap.select()
  52.  
  53. searchString = ('(before "%s")' % purgeDate.strftime("%d-%b-%Y"))
  54. type, data = imap.search (None, searchString)
  55.  
  56. y_or_n = raw_input("Delete %d messages? " % len(data[0].split(' ')))
  57. if (not (y_or_n == 'y' or y_or_n == 'Y')): return
  58.  
  59. for num in data[0].split():
  60. imap.store(num, '+FLAGS', '\\Deleted')
  61.  
  62. if verbose:
  63. typ, data = imap.fetch(num, '(BODY[HEADER.FIELDS (FROM SUBJECT DATE)])')
  64.  
  65. emailBody = data[0][1]
  66. mail = email.message_from_string(emailBody)
  67.  
  68. # print "--"
  69. # print ':' + mail['Subject'] + ':'
  70. # print ':' + mail['From'] + ':'
  71. # print ':' + mail['Date'] + ':'
  72. # print "--"
  73.  
  74. try:
  75. subjectStr = email.header.decode_header(mail['Subject'])
  76. fromStr = email.header.decode_header(mail['From'].replace('"', ''))
  77. date = datetime.date.fromtimestamp(time.mktime(rfc822.parsedate(mail['Date'])))
  78. except email.header.HeaderParseError:
  79. print "error"
  80. pass
  81.  
  82. print "Deleted : " + decodeHeaderStr(subjectStr) + ":::" \
  83. + decodeHeaderStr(fromStr) + ":::" + date.strftime("%m-%d-%y")
  84.  
  85. imap.expunge() # permanently remove deleted items
  86.  
  87. imap.close()
  88. imap.logout()
  89.  
  90. if __name__ == '__main__':
  91. if gmail_user == '':
  92. gmail_user = raw_input('id: ')
  93. if gmail_pass == '':
  94. gmail_pass = getpass.getpass()
  95.  
  96. process()
Add Comment
Please, Sign In to add comment