Archives

Counting Messages in IMAP Folders in Python

Continuing on my last post (), I wanted to show a snippet of Python code that will list a set of IMAP folders and count the number of messages in them. You give it a starting folder and it lists that folder plus all/any sub-folders and their message counts. At the very end it prints a total message count.

Listing IMAP Mailboxes with Python

I’ve been working on some Python scripts recently to manage my IMAP mailboxes and the information I found on the internet was fairly good, but lacked a completeness that my newbie Python skills required. So, I figured I’d post a complete example to list mailboxes (folders) for your IMAP account. This was developed using Python 3.3.

I hope this code snippet help you on your way to Python IMAP goodness. If not, it will at least server as a reminder to myself the next time I need to do something like this.

PHP Script To Monitor FTP Directory Changes

I recently had the need to be able to monitor a directory on an FTP server for changes and to then be notified of those changes. I’ve been working a lot in PHP lately so I decided to use that to implement my script.

FTP Access

FTP (file transfer protocol) access in PHP is a breeze. It’s as simple as this:

Easy, right? Of course I left out a few pieces of the puzzle, but I just wanted to show how easy it is to actually get to an FTP server, login and get a directory listing.

Comparisons

After retrieving the listing which is an array I remove out the “.” and “..” listings as they are special system directories meaning “the current directory” and “the parent directory” respectively.

Now the header for this section is Comparisons, so what exactly are we comparing to? Each time this script runs we store a serialized version of this array out to file. I read the file into an array and compare it with the one we just created from the FTP directory.

Now that we have an array of files (and directories) that we just pulled from the FTP server and an array that we saved from the last time we ran we can just compare the two.

Finally, I write the contents of the new array back out to the cache file so we can use it to compare on the next run.

Summary and Download

So that’s it! Pretty simple. On my server I pre-pended the following to the file:
#!/usr/bin/env php
and changed the file mode so that it could be executed. I then setup a cron job to run at 8 o’clock every morning like this:

> crontab -e

# This is added to crontab
0 8 * * * ~/ftpMonitor.php

Here is the complete file in a zip file. Open the file in any text editor and you will see a configuration section at the top where you can set your FTP host information and email information.

ftpMonitor.zip

I hope you have enjoyed this short tutorial and may possibly find it useful. If you have any comments or suggestions for improvement please feel free to leave those in the comments section below. Thanks for stopping by!