472,330 Members | 1,503 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,330 software developers and data experts.

Mailbox cleaner on an IMAP basis?

Hi all!

As I saw Alex Martelli's post about a mbox cleaner based on POP3, I thought,
it could be possible to do that based on IMAP too. That way I could ask the
server for mails having attached EXE files and delete all those mails on the
server. This would save me a lot of traffic over my phone line connection.

But I'm missing one important thing: How do I get the server to tell me
about attachments.

What I've found out so far is how to get at the fields:

r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])")

Alas, there's no such thing like 'filename' or 'attachments'.

And

r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS (Content-type)])")

doesn't show a file name either.

Any hints?

Best regards
Franz GEIGER

Jul 18 '05 #1
5 4523

"F. GEIGER" <fg*****@datec.at> wrote in message
news:3f******@news.swissonline.ch...
Hi all!

As I saw Alex Martelli's post about a mbox cleaner based on POP3, I thought, it could be possible to do that based on IMAP too. That way I could ask the server for mails having attached EXE files and delete all those mails on the server. This would save me a lot of traffic over my phone line connection.

But I'm missing one important thing: How do I get the server to tell me
about attachments.

What I've found out so far is how to get at the fields:

r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])")

Alas, there's no such thing like 'filename' or 'attachments'.

And

r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS (Content-type)])")

doesn't show a file name either.

Any hints?
Right now, I'd simply like something that would clean out an
IMAP mailbox on a regular basis. Most of the worm generated
garbage is going into one of two boxes on my server, and I get maybe
one legitimate e-mail in those two boxes every couple of weeks.
I can stand to lose that level of e-mail, I can't stand to exceed my disk
quota and lose lots of legitimate mail every few hours.

Could you post the code you've got so far?

Thanks.

John Roth
Best regards
Franz GEIGER


Jul 18 '05 #2
Well, John,

I've stopped here, because I could not figure out how to get at the ids of
mails with attachments. And if I had that missing link, I'd run into the
next hindrance: How can I delete a single message? IMAP4::delete() deletes a
whole mailbox, not just a single mail.

So my code really is only a few lines so far:

i = IMAP4(myDomain)
i.login(myUser, myPassword)
i.select() # Select INBOX
r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])") # Check 1st mail

Seems I have to get a book about IMAP and how to use it...

Kind regards
Franz


"John Roth" <ne********@jhrothjr.com> schrieb im Newsbeitrag
news:vm************@news.supernews.com...

"F. GEIGER" <fg*****@datec.at> wrote in message
news:3f******@news.swissonline.ch...
Hi all!

As I saw Alex Martelli's post about a mbox cleaner based on POP3, I

thought,
it could be possible to do that based on IMAP too. That way I could ask

the
server for mails having attached EXE files and delete all those mails on

the
server. This would save me a lot of traffic over my phone line connection.
But I'm missing one important thing: How do I get the server to tell me
about attachments.

What I've found out so far is how to get at the fields:

r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])")

Alas, there's no such thing like 'filename' or 'attachments'.

And

r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS (Content-type)])")

doesn't show a file name either.

Any hints?


Right now, I'd simply like something that would clean out an
IMAP mailbox on a regular basis. Most of the worm generated
garbage is going into one of two boxes on my server, and I get maybe
one legitimate e-mail in those two boxes every couple of weeks.
I can stand to lose that level of e-mail, I can't stand to exceed my disk
quota and lose lots of legitimate mail every few hours.

Could you post the code you've got so far?

Thanks.

John Roth

Best regards
Franz GEIGER



Jul 18 '05 #3
Quoth "F. GEIGER" <fg*****@datec.at>:

| I've stopped here, because I could not figure out how to get at the ids of
| mails with attachments. And if I had that missing link, I'd run into the
| next hindrance: How can I delete a single message? IMAP4::delete() deletes a
| whole mailbox, not just a single mail.
|
| So my code really is only a few lines so far:
|
| i = IMAP4(myDomain)
| i.login(myUser, myPassword)
| i.select() # Select INBOX
| r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])") # Check 1st mail
|
| Seems I have to get a book about IMAP and how to use it...

The IMAP4rev1 RFC of course covers these things, with examples.
2060, I think it is. A message takes two steps to delete: first,
set a \Deleted flag on it, and then invoke expunge on the folder,
which will remove all delete-flagged messages in the folder.

Donn Cave, do**@drizzle.com
Jul 18 '05 #4
> server for mails having attached EXE files and delete all those mails on the
server. This would save me a lot of traffic over my phone line connection.


I use a Python script which is run via cron every hour on
a machine with internet connectivity.

It downloads all mails, parses them and does whitelist
filtering but could be easily extentend.

All filtered mails are removed from the mailbox and
stored locally. This mbox file can then be
retrieved by scp/ftp.

Cleaning only every hour has proved to be enough.

Since my script has been running without any
trouble for almost half a year I thought it
may be a basis for ideas or customizing, so
I'll append it to this posting.

Ciao,
Dominic

P.S. You'll need the tpg-parser generator for Python.

Jul 18 '05 #5
Ok, I came up with this so far, many thanks to all who contributed!

Best regards
Franz GEIGER
import os.path, re
from imaplib import *
class Finder:
def __init__(self, text):
self._value = None
results = self._rex.findall(text)
if results:
self._value = results[0]
return

def value(self):
return self._value
class UIDfinder(Finder):

_rex = re.compile(r'UID (\d+)')
class FileNameFinder(Finder):

_rex = re.compile(r'\("application" ".+?" \("name" "(.+?)"\)')

def ft(self):
if not self._value:
return None

root, ft = os.path.splitext(self._value)
return ft
class SenderFinder(Finder):

_rex = re.compile(r'From\: (.+)\r', re.M | re.I)

class SubjectFinder(Finder):

_rex = re.compile(r'Subject\: (.+)\r', re.M | re.I)
class DateFinder(Finder):

_rex = re.compile(r'Date\: (.+)\r', re.M | re.I)
class MessageSummary:
def __init__(self, uid, fileName, text):
if not fileName:
fileName = ''

self._uid = uid
self._fileName = fileName

self._sender = ''
self._subject = ''
self._date = ''

f = SenderFinder(text)
if f.value():
self._sender = f.value()

f = SubjectFinder(text)
if f.value():
self._subject = f.value()

f = DateFinder(text)
if f.value():
self._date = f.value()

return

def __str__(self):
return self.formatted()

def formatted(self):
return "From : %s\nSubject : %s\nAttachment: %s\nFile-Name :
%s" % (self._sender, self._subject, self._date, self._fileName)

def uid(self):
return self._uid
class Deleter:
def __init__(self, server, messageSummaries):
self._server = server
self._messageSummaries = messageSummaries
self._uids = [ms.uid() for ms in self._messageSummaries]
return

def run(self):
uids = ','.join(self._uids)
r = self._server.uid("STORE", uids, "+FLAGS.SILENT", "(\Deleted)")[0]
if r in ("OK", "Ok", "ok"):
return ''
else:
return "Error - Could Not Delete Messages"
class Expunger:
def __init__(self, server):
self._server = server
return

def run(self):
self._server.expunge()
return
print "Logging in."
server = IMAP4("<myDomain>")
server.login("<myUserName>", "<myPassword>")
server.select()
print "Begin to cleanup mailbox."
messagesToDelete = []
i = 0
while (1):
i += 1

r, d = server.fetch(i, "(UID BODY)")
if r == 'NO' or d[0] is None:
break
uid = UIDfinder(d[0]).value()
fnf = FileNameFinder(d[0])
fn = fnf.value()
if not fn:
print '.',
continue

ft = fnf.ft()

r, d = server.fetch(i, "(BODY.PEEK[HEADER.FIELDS (Date From Subject)])")

ms = MessageSummary(uid, fn, d[0][1])

if ft.lower() == ".exe":
print '*',
messagesToDelete.append(ms)
else:
print '.',
if messagesToDelete:
print "\n" * 4
print "%d messages are tagged to be deleted: " % len(messagesToDelete)
for ms in messagesToDelete:
print ms.formatted()
print
print
if raw_input("Shall I delete them now (y/n)? ") == 'y':
print 'Working...'
d = Deleter(server, messagesToDelete)
d.run()
e = Expunger(server)
e.run()
print "Done. "
else:
print
print "No messages to delete. "
raw_input("Press any key to exit...")


"Donn Cave" <do**@drizzle.com> schrieb im Newsbeitrag
news:1064298380.225028@yasure...
Quoth "F. GEIGER" <fg*****@datec.at>:

| I've stopped here, because I could not figure out how to get at the ids of | mails with attachments. And if I had that missing link, I'd run into the
| next hindrance: How can I delete a single message? IMAP4::delete() deletes a | whole mailbox, not just a single mail.
|
| So my code really is only a few lines so far:
|
| i = IMAP4(myDomain)
| i.login(myUser, myPassword)
| i.select() # Select INBOX
| r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])") # Check 1st mail
|
| Seems I have to get a book about IMAP and how to use it...

The IMAP4rev1 RFC of course covers these things, with examples.
2060, I think it is. A message takes two steps to delete: first,
set a \Deleted flag on it, and then invoke expunge on the folder,
which will remove all delete-flagged messages in the folder.

Donn Cave, do**@drizzle.com

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Alex Martelli | last post by:
All my mailboxes have been filling up with files of about 130k to 150k, no doubt copies of some immensely popular virus. So, I've no doubt lost...
2
by: Lindstrom Greg - glinds | last post by:
I have written a script to monitor my MS Exchange mailbox for certain messages and post information to an MS SQL Server Database. Everything works...
1
by: RH | last post by:
I need to be able to search, read and move mail into different folders in an Exchange 2000 mailbox. Can someone please point me in the right...
5
by: Antoon Pardon | last post by:
This little program gives IMO a strange result. import imaplib user = "cpapen" cyr = imaplib.IMAP4("imap.vub.ac.be") cyr.login("cyrus",...
4
by: bill | last post by:
I am in preliminary design of a contact management program. The user would like to use his current mail server (POP3 - remote). I have done some...
3
by: WhatsPHP | last post by:
Hi Can anyone please point me to good PHP software that can manage an IMAP email inbox from PHP? So basically from the admin panel, the users...
0
by: jesse.k.rosenthal | last post by:
Dear all, I'm trying to figure out if mailbox will let me get the flags of a Maildir message without running get_message on it, and reading the...
1
by: rishab | last post by:
Hey everyone, I want to print the folder list of my mailbox using python (IMAP4), and with hierarchy, i.e. it should print all the names of the...
5
by: Craig Buchanan | last post by:
I would like to monitor a POP3 mailbox with multiple clients. However, I want to ensure that each message is processed by only one client. In...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.