markhuge

New Mail Notification with OfflineIMAP (or any Maildir)

Published by Mark on

There’s a really simple way to check for new msgs that will satisfy 90% of people who search for this:

  #!/bin/sh
  find $HOME/mail/*/INBOX/new/ -type f | wc -l

If that’s all you need, you’re welcome.

I’m a weirdo and I have really specific needs. I don’t care about new (unread) messages, I care about new msgs between syncs (unread or not). I also want a notification when I’ve started a sync and when it’s complete.

To do this, I wrapped offlineimap with a shell script:

#!/bin/sh

# Count mail
count() { 
  find "$HOME"/mail/*/INBOX -type f | wc -l
}

# Make sure offlineimap isn't already running
if [ -z "$(pgrep offlineimap)" ]; then

  # Default msg
  msg="Done syncing mail"

  notify-send "Syncing mail..."

  # Get old email count
  old=$(count)
  offlineimap

  # Get email count after sync
  new=$(count)

  # Overwrite msg if new emails are found
  if [ "$new" -gt "$old" ]; then
    msg="$((new - old)) new emails"
  fi

  notify-send "${msg}"

else
  notify-send "Mail sync already running"
fi