View source for pythontips

{{anchor href="top"}}
Hits :  **{{hits}}**


== Python Tips ==

{{ToC from="h2" to="h3"}}

 ===  How to remove a specific mail from a mbox  === 

%%(python)
#!/usr/bin/env python
# Created by Evaggelos Balaskas on Sun Jul 25 06:36:29 EEST 2010
# Last edit on Thu Jul 29 17:56:08 EEST 2010
# Remove mails from mbox by subject

import sys
import mailbox
import re

SUBJECTS = (
        'automatically rejected mail',
        'delivery failure',
        'delivery notification',
        'delivery status notification',
        'failure notice',
        'mail delivery failed',
        'mail delivery failure',
        'nondeliverable',
        'returned mail',
        'undeliverable',
        'undelivered',
        'warning: could not send message for past'
)

if len(sys.argv) == 2:
    for message in mailbox.mbox( sys.argv[1] ) :
        s = message['subject']
        if s is not None :
                flag = 1
                for i in SUBJECTS:
                        m = re.search ( i, str(s), re.I )
                        if m is not None :
                                flag = 0
                                break
                if flag :
                        print message
        else:   
                print message
else:   
        print "Usage should be: " + sys.argv[0] + " mbox > new.mbox"
%%

((#top))
-----------

 === Remove duplicate mails from mailbox === 

%%(python)
#!/usr/bin/env python
# Created by Evaggelos Balaskas on Thu Jul 29 21:22:41 EEST 2010
# Remove duplicate mails from mbox using message-id

import sys
import mailbox

if len(sys.argv) == 2:
        mid = []

        for message in mailbox.mbox( sys.argv[1] ) :
                s = message['message-id']
                if s not in mid:
                        mid.append(s)
                        print message
else:
        print "Usage should be: " + sys.argv[0] + " mbox > new.mbox"

%%

((#top))
-----------


 === Remove duplicate mails from mailbox (using sets instead of lists) === 

%%(python)
#!/usr/bin/env python
# Created by Evaggelos Balaskas on Thu Jul 29 21:22:41 EEST 2010
# Remove duplicate mails from mbox using message-id
# Based on sets !

import sys
import mailbox

if len(sys.argv) == 2:
	uniqs = set()
	
	for message in mailbox.mbox( sys.argv[1] ) :
		s = message['message-id']
		if s not in uniqs:
			uniqs.add(s)
			print message
else:
        print "Usage should be: " + sys.argv[0] + " mbox > new.mbox"
%%

((#top))
-----------