Thursday, December 22, 2011

Managing your IMAP account using Perl


This perl script will give you a basic idea of how your IMAP account can be managed  via perl.  I have been using perl to manager certain tasks with my GMail account ( GMail provides both POP and IMAP services).

We make use of the Mail::IMAPClient perl module for manipulating imap accounts.  This script also prompts for a password from command line so that you don't have to hard code your password in the script.


### Module loading

### Mail::IMAPClient for manipulating IMAP accounts
use Mail::IMAPClient;

### Term::ReadKey is for accepting passwords from terminal
use Term::ReadKey;

### Ask for password
print "Enter Password:";
               ReadMode('noecho');
               chomp ( my $imapPassword = ReadLine(0)) ;
               ReadMode('restore');
print "\n";

### Provide your imap username here
my $imapUser = 'your.imap.user' ;

### Provide your imap server name
my $imapServer = 'your.imap.server.name';

### Provide your imap server port number, default is 993.
my $imapPort = 993;

my $imap = Mail::IMAPClient->new(
    Server   => $imapServer,
    User     => $imapUser,
    Port     => $imapPort,
    Password => $imapPassword,
    Ssl      => 1,
  )

or die "Can't connect to $imapServer as $imapUser: $@";

### You are now logged into the imap account.  Play around a bit

### Print all folders
my $folders = $imap->folders or die "List folders error: ", $imap->LastError, "\n";
foreach ( @$folders )  { print $. , " ) " , $_ ,"\n"; }

### Count messages in the Sent folder
my $msgcount = $imap->message_count('Sent');
print "Count $msgcount\n";

### Process all emails in the folder "Work"

## Start by selecting the Work folder
$imap->select('Work') or
    die("Couldn't select Work folder", $!);

## Load all message ids in Work folder to @msgs
my @msgs = $imap->messages or die "Couldn't get messages: $@\n";

## Backup message to $file

my $TS = time;
my $FILE = "imap_bakup_".$TS;
open MAILBACKUP, ">>", $FILE or die "Couldn't open $FILE"
print MAILBACKUP "Starting backup at time : $TS\n";}

foreach my $msgid (@msgs)
{
 $imap->message_to_file(MAILBACKUP,$msgid) or die "Couldn't backup $msgid: $@\n";
}

print MAILBACKUP "Finished backup";
close BACKUP;

## Delete all messages in "Work" folder
$imap->delete_message(\@msgs) or die "Couldn't delete message in folder Work: $@\n";

### Create new folder "Life"
$imap->create("Life") or die "Couldn't create folder Life: $@\n";

### Delete the folder "Life"
$imap->delete("Life") or die "Couldn't delete folder Life: $@\n";

### Expunge messages marked as deleted in the selected folder
$imap->expunge() or die "Couldn't expunge: $@\n";

### Close the selected folder
$imap->close or die "Couldn't close: $@\n";

### Logout IMAP
$imap->logout