# 08/09/2002 - 16:55:34
# (C) 2002 Romain GUY, licensed under GNU GPL-2
#
# Convert a given Outlook Express (5 or 6) mailbox file to
# a standard Unix mailbox file (.mbx)

from oe.mailbox import *
import os.path
import sys
from time import gmtime, strftime

if len(sys.argv) < 2:
  print os.path.basename(sys.argv[0]), "[outlook express dbx file]"
  print "(C)2002 Romain GUY"
  sys.exit(1)

try:
  dbx = open(sys.argv[1], "rb", 0)

  header = dbxFileHeader(dbx)

  if header.isMessages():
    info = dbxFileInfo(dbx, header.getEntry(dbxFileHeader.FH_FILE_INFO_LENGTH))

    entries = header.getEntry(dbxFileHeader.FH_ENTRIES)
    address  = header.getEntry(dbxFileHeader.FH_TREE_ROOT_NODE_PTR)

    if address and entries:
      mbx = open(os.path.basename(os.path.splitext(sys.argv[1])[0]) + ".mbx", "w")

      tree = dbxTree(dbx, address, entries)

      for i in range(entries):
        address = tree.getValue(i)
        messageInfo = dbxMessageInfo(dbx, address)

        if messageInfo.isIndexed(dbxMessageInfo.MI_MESSAGE_ADRESS):
          print "Processing message", i, "..."

          messageAddress = messageInfo.getValueAsLong(dbxMessageInfo.MI_MESSAGE_ADRESS)
          message        = dbxMessage(dbx, messageAddress)

          mbx.write("From oe2mbox@jext.org ")
          mbx.write(strftime("%a %b %d %H:%M:%S MET %Y", gmtime()))
          mbx.write("\n")
          mbx.write(message.getText().replace("\r\n", "\n") + "\n")

      mbx.close()
    else:
      print "[NOTICE] Corrupted mailbox file"
  else:
    print "[NOTICE] The specified mailbox contains no messages"

except Exception, (strerror):
  print "[ERROR] An unexpected error has happened during the process"

dbx.close()

# end of oe2mbx.py
