473,800 Members | 2,930 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4625

"F. GEIGER" <fg*****@datec. at> wrote in message
news:3f******@n ews.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********@jhr othjr.com> schrieb im Newsbeitrag
news:vm******** ****@news.super news.com...

"F. GEIGER" <fg*****@datec. at> wrote in message
news:3f******@n ews.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.co m
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.finda ll(text)
if results:
self._value = results[0]
return

def value(self):
return self._value
class UIDfinder(Finde r):

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

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

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

root, ft = os.path.splitex t(self._value)
return ft
class SenderFinder(Fi nder):

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

class SubjectFinder(F inder):

_rex = re.compile(r'Su bject\: (.+)\r', re.M | re.I)
class DateFinder(Find er):

_rex = re.compile(r'Da te\: (.+)\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(te xt)
if f.value():
self._sender = f.value()

f = SubjectFinder(t ext)
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, messageSummarie s):
self._server = server
self._messageSu mmaries = messageSummarie s
self._uids = [ms.uid() for ms in self._messageSu mmaries]
return

def run(self):
uids = ','.join(self._ uids)
r = self._server.ui d("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.ex punge()
return
print "Logging in."
server = IMAP4("<myDomai n>")
server.login("< myUserName>", "<myPasswor d>")
server.select()
print "Begin to cleanup mailbox."
messagesToDelet e = []
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 '*',
messagesToDelet e.append(ms)
else:
print '.',
if messagesToDelet e:
print "\n" * 4
print "%d messages are tagged to be deleted: " % len(messagesToD elete)
for ms in messagesToDelet e:
print ms.formatted()
print
print
if raw_input("Shal l I delete them now (y/n)? ") == 'y':
print 'Working...'
d = Deleter(server, messagesToDelet e)
d.run()
e = Expunger(server )
e.run()
print "Done. "
else:
print
print "No messages to delete. "
raw_input("Pres s any key to exit...")


"Donn Cave" <do**@drizzle.c om> 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.co m

Jul 18 '05 #6

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

Similar topics

9
2739
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 lots of real mail because of "mailbox full" conditions (the proliferating fake bounce messages more or less ensure nobody knows their mail to me has bounced, either). As an emergency response I and Anna developed, over the last half hour, a small Python script to be run from cron every few...
2
4641
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 great except that each time I run the script I am prompted by Windows to choose the profile of the mailbox via a dialog box. I'd like to run the script every hour, so this is not good. Is there any way to either specify the profile or accept the default? Thanks for any help you can send my...
1
334
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 direction? Thanks
5
1813
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", "cOn-A1r") rc, lst = cyr.list('""', "user/%s/*" % user) for el in lst:
4
4175
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 reading on the IMAP functions but am unclear if the following is possible: Using the IMAP functions can I write a PHP script to: scan the subject lines of all mail in the mailbox ? pop just certain messages from the inbox ? delete those messages from the inbox ?
3
1610
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 will be able to see all the emails, read emails, move emails to folders, delete emails and they wont have to leave the admin section. I have seen similar stuff happen in SugarCRM. It does not have to be as functional as webmail clients, Just the basics will do. TIA
0
1447
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 whole message. It seems like it should work by doing this: 2102 But then,when I try to get_flags on msg, I get nothing
1
1591
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 folders of my mailbox and the folders within them. Can anyone please help me with this.
5
2679
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 essence, I would like to treat a POP3 mailbox like a queue. From what I've read thus far, atomic message access (if this is the right term) isn't a native feature of the POP3 protocol. Am I mistaken? My approach thus far, is to have one thread connect to the mailbox periodically, look for new...
0
9689
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9550
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10495
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10269
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10248
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10032
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5597
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4148
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.