Deian Stefan


Maildir::Lite - A very simple implementation of Maildir


Write to a file handle:

   my $mdir=Maildir::Lite->new(dir=>'/home/d/.maildir');
   # write messages
   my ($fh,$status)=$mdir->creat_message();
   die "creat_message failed" if $status;

   print $fh "Content-Type: text/plain\n"
             ."Date: $date\n"
             ."From: $from\n"
             ."To: $to\n"
             ."Subject: $subject\n\n"

   die "delivery failed!\n" if $mdir->deliver_message($fh);

Write string and deliver message directly:

   my $status=$mdir->creat_message($email_content);
   die "creat_message failed" if $status;

Read new messages given a file handle:

   my ($fh,$status)=$mdir->get_next_message("new");
   unless($status) {
      while(<$fh>) { # read message
   $mdir->act($fh,'S'); # flag message as seen and move to cur

Read new messages into an array and flag message as seen while moving it to cur:

   my ($fh,$status)=$mdir->get_next_message("new",\@lines,'S');


This is a simple and very light implementation of Maildir as specified by D. J. Bernstein at

This module provide the user with a simple interface to reading and writing email messages to maildir folders. Some additional useful features are also supported (e.g. support for additional subdirecties and user defined actions for the maildir flags).



   my $maildir = Maildir::Lite->new();

   my $maildir = Maildir::Lite->new(create=>1,
      dir=>'.maildir/', mode=>0750, sort=>'asc');
  • create - if set to 0, the directory and the subdirectories will not be created and are assumed to exist.

  • dir - the maildir directory; it defaults to ~/.maildir (if $ENV{HOME} exits).

  • mode - the (default 0750) directory permissions of dir and sub-directories.

  • uniq - set unique integer which will be otherwise randomly generated for filennames; it is important that uniq is actually unique.

  • sort - the read messege sorting method. See "sort".


Add a specific $action (function or 'close') to $folder for the $flag flag.

For example, if you wish to move files from new to trash when given the flag 'T' (or 'trash'):


Specifiying 'close' closes the file, without appending the info or moving the file.

The default action for folder new is to move it to cur and append the flag 'S' flag. Reading messages from cur or tmp by default only closes the file.

Returns 0 upon success, -1 otherwise.

Example of action function:

   sub new_to_trash {
      my ($path, $filename,$action)=@_;
      my $flag=uc(substr($action,0,1));

      if($flag eq 'T') {
         if(-d "$path/trash/") { 
            my $old="$path/new/$filename";
            my $new="$path/trash/$filename:2,$flag";

            if(rename($old,$new)) {
               return 0;
            } else {
               die("failed to rename \'$old\' to \'$new\'");
         } else {
            die("\'$path/trash\' directory does not exist");
      return -1;


Set the maildir path:


Get the maildir path:



Set the mode for creating the directory and subdirectories tmp, cur and new:


Get the mode:



Create the directory and subdirectories tmp, cur and new if they do not already exist:


As above, but create the additional directories trash, sent:


This subroutine does not need to be explicitly called before creating new messages (unless you want to create folders other than tmp, new, and cur).

This subroutine returns 0 if the directories were created (or exist), otherwise it returns -1 and a warning with carp.


Get a file handle $fh to a unique file in the tmp subdirectory:

   my ($fh,$status) = $maildir->creat_message();

Write message to unique file in tmp subdirectory which is then delivered to new:

   my $status=$maildir->creat_message($message);

Return: $status is 0 if success, -1 otherwise. $fh is the filehandle (undef if you pass create_message an argument).


Given file handle $fh, deliver message and close handle:


Returns 0 upon success, -1 otherwise.


Deliver all messages and close all handles:


Returns 0 upon success, -1 otherwise.


Get the current method for sorting messages:

   my $sort=$maildir->sort();

Set the sorting function of method:

   $maildir->sort('non'); # no specific sorting

   $maildir->sort('asc'); # sort based on mtime in increasing order

   $maildir->sort('des'); # sort based on mtime in decreasing order

   $maildir->sort(\&func); # sort based on user defined function

Example of sorting function which sorts according to a line in the message beggining with "sort:" followed by possible spaces and then a digit:

   sub func {
      my ($path,@messages)=@_;
      my %files; my @newmessages;

      foreach my $file (@messages) {
         my $f;
         open($f,"<$path/$file") or return @messages; #don't sort
         while(my $line=<$f>) {
            if($line=~m/sort:\s*(\d)+$/) { # string where sort info is

      @newmessages= sort { $files{$a} <=> $files{$b}} keys %files;

      return @newmessages;


Get the next message (as file handle) from directory new:

   my ($fh,$status)=$maildir->get_next_message("new");

NOTE: It is important to properly close file handle once finished with "close_message" or "act".

Read lines of next message in array @lines then, close message and execute the action specified for flag 'P' (default for new: move to cur and append ':2,P'):

   my $status=$maildir->get_next_message("new",\@lines,'passed');

Return: $status is 0 if success, -1 otherwise. $fh is the filehandle (undef if you pass get_next_message a second argument).


Force a readdir during the next "get_next_message". This is useful if you are reading messages from new and then from cur as some of the messages will be moved there.



Given file handle $fh, close handle:


Returns 0 upon success, -1 otherwise.


Given file handle $fh, and flag ('P','R','S','T','D','F') close message, append the info and execute the specified action for the flag:


Returns 0 upon success, -1 otherwise.


Writing messages

The example shows the use of this module with MIME::Entity to write messages.

   use strict;
   use warnings;
   use MIME::Entity;
   use Maildir::Lite;

   my $mdir=Maildir::Lite->new(dir=>'/tmp/.your_mdir');

   # print message to file handle
   sub print_message {
      my ($from,$to,$subj,$message,$fh)=@_;
      my $date=localtime;
      my $msg = MIME::Entity->build(
            Type        => 'text/plain',
            Date        => $date,
            From        => $from,
            To          => $to,
            Subject     => $subj,
            Data        => $message);


   # write messages to maildir folder
   sub  write_message {
      my ($from,$to,$subj,$message)=@_;
      my ($fh,$stat0)=$mdir->creat_message();

      die "creat_message failed" if $stat0;


      die "delivery failed!\n" if $mdir->deliver_message($fh);

   write_message('', '','Hi!','One line message');
   write_message('', '','Bye!','Who are you?');
   write_message('', '','Hello!','You again?');

Reading messages

The example shows the use of this module with MIME::Parser to read messages.

   use strict;
   use warnings;
   use MIME::Parser;
   use Maildir::Lite;

   my $mdir=Maildir::Lite->new(dir=>'/tmp/.your_mdir');
   # move file from new to trash with changed filename

   sub read_from {
      my $folder=shift;
      my $i=0;


      print "$folder:\n|".("-"x20)."\n";

      while(1) {
         my $parser = new MIME::Parser;

         my ($fh,$status)=$mdir->get_next_message($folder);
         last if $status;

         my $entity=$parser->parse($fh);

         print "Message $i:\n".$entity->stringify."\n";

         if($mdir->act($fh,'S')) { warn("act failed!\n"); }

      print "|".("-"x20)."\n\n";


   read_from("cur"); # to see the force_readdir in action


There is already an implementation of Maildir, Mail::Box::Maildir, which is great, but more bulky and complicated.

Maildir specifications at


Version 0.01


Deian Stefan, <stefan at>


Please report any bugs or feature requests to bug-maildir-lite at, or through the web interface at I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.


You can find documentation for this module with the perldoc command.

    perldoc Maildir::Lite

You can also look for information at:


Copyright 2008 Deian Stefan, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.