473,881 Members | 1,755 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 4630

"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
2740
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
4644
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
1819
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
4181
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
1612
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
1450
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
1596
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
2684
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
9930
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
9776
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
11103
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
10720
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
10819
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
9555
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5781
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4597
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
3
3225
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.