popclean.py

#!/usr/bin/env python

"""
$Id: popclean.py 170 2001-01-30 23:55:58Z david $

Facilitates the removal of messages from a user's POP3 mailbox.
"""


import getpass, poplib, sys, getopt, string
from popcount import popcount

SHORT_OPTS   = "a:m:r:"
ALL_OPT      = "-a"
MESSAGES_OPT = "-m"
RANGE_OPT    = "-r"

USAGE = """\
Usage: %s [-a] [-m <message numbers>] [-r <num-num>] <server> <username> 
""" % sys.argv[0]

DeleteAll = 0


def popclean (hostname, username, password, messages):
	"""
	Deletes a message from the given server for the given user based
	upon the list of message numbers, "messages".
	"""
	try:
		popserver = poplib.POP3(hostname)
		popserver.user(username)
		popserver.pass_(password)
	except (poplib.error_proto, socket.error), reason:
		sys.stderr.write("Error: %s\n" % reason)
		sys.exit(1)

	for message in messages:
		popserver.dele(message)

	popserver.quit()


def parseArgs ():
	"""
	From the command line arguments we determine the list of message
	numbers to be deleted and the username and hostname to be used.
	"""
	global DeleteAll
	opts = []
	args = []

	messages  = []

	# Obtain the command line options and arguments
	try:
		opts, args = getopt.getopt(sys.argv[1:], SHORT_OPTS)
	except getopt.error, reason:
		sys.stderr.write("%s\n" % reason)
		sys.stderr.write(USAGE)
		sys.exit(1)

	# Delete all messages or only some?
	for opt, val in opts:
		if opt == MESSAGES_OPT:
			f = lambda x: string.atoi(x)
			val = string.split(val)
			val = map(f, val)
			messages.extend(val)
		if opt == ALL_OPT:
			DeleteAll = 1
		if opt == RANGE_OPT:
			begin, end = string.split(val, "-")
			begin = string.atoi(begin)
			end   = string.atoi(end) + 1
			messages.extend(range(begin, end))
	
	# Get the host and user arguments
	try:
		hostname = args[0]
		username = args[1]
	except IndexError:
		sys.stderr.write("%s\n" % USAGE)
		sys.exit(1)

	return username, hostname, messages


def main ():
	username, hostname, messages = parseArgs()
	password = getpass.getpass()

	if DeleteAll:
		nMessages = popcount(hostname, username, password)
		messages  = range(nMessages)

	popclean(hostname, username, password, messages)


if __name__ == '__main__':
	main()