Created
March 12, 2014 03:39
-
-
Save aminamid/9500407 to your computer and use it in GitHub Desktop.
pythonでPOP SSLを使い大きい順に5個メッセージを表示又は削除する
This file contains hidden or 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/env python | |
# -*- coding: utf-8 -*- | |
import sys | |
import time | |
import poplib | |
import email | |
def get_subject(msg): | |
h = email.Header.decode_header(msg.get('subject')) | |
return unicode(email.header.make_header(h)).encode('utf-8') | |
def get_from(msg): | |
h = email.Header.decode_header(msg.get('from')) | |
return unicode(email.header.make_header(h)).encode('utf-8') | |
def get_date(msg): | |
mdate = email.utils.parsedate(msg.get('date')) | |
return time.strftime('%Y/%m/%d %H:%M:%S', mdate) | |
def get_body(msg): | |
body = msg.get_payload(decode=True) | |
char = msg.get_param('charset') | |
return unicode(body, char, 'ignore').encode('utf-8') | |
argvs = sys.argv | |
argc = len(argvs) | |
print argvs | |
print "number of args: {0}".format(argc) | |
if (argc != 6): | |
print 'Usage: # python {0} <popserver> <ssl_port> <user> <pass> <"chk"|"dele">'.format(argvs[0]) | |
quit() | |
pop = poplib.POP3_SSL(argvs[1],port=int(argvs[2])) | |
pop.set_debuglevel(1) | |
pop.user(argvs[3]) | |
pop.pass_(argvs[4]) | |
raw_all_list=pop.list()[1] # 2番目に文字列のリストが入っている | |
all_list=map( (lambda x: x.split(' ')), raw_all_list) #文字列のリストをリストに変換して2次元配列を作る | |
all_list.sort(cmp=lambda x,y: cmp(int(x[1]), int(y[1]))) #メッセージサイズを整数としてsortする | |
target_msgs = all_list[-5:] | |
target_list =[] | |
for msg in target_msgs: | |
raw_blob_list = pop.retr(int(msg[0]))[1] | |
raw_blob = email.message_from_string('\n'.join(raw_blob_list)) | |
target_list.append([msg[0], msg[1], get_date(raw_blob), get_subject(raw_blob), get_from(raw_blob)]) | |
for item in target_list: | |
print "{0}, size: {1:>10}, {2:10},{3}".format(item[2],item[1],item[4][0:20],item[3]) | |
if (argvs[5]=='dele'): | |
pop.dele(int(msg[0])) | |
if (argvs[5]=='dele'): time.sleep(10) | |
pop.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment