How to download all the e-mail messages from POP3 server to a single text file with mailx

emailfetchmailmailx

I would like to download all the e-mails in my old e-mail server. It uses POP3 and I'm interested in e-mails in "Inbox" and "Sent" folders. Once I have downloaded all the messages, I would like to make a script which lists all the e-mails between my e-mail address and one certain e-mail address in chronological fashion into single text file.

However, at first, I think I need to download all the messages to a single file with headers including dates and then create a sorting script. How to approach this?

I have used mailx in scripts for sending mails, but is it possible to use mailx to download all the mails from POP3 server into a single file?

Best Answer

Traditional mailx does not support IMAP or POP, but the one that comes with Linux does.

For your particular problem, I recommend using fetchmail instead. You can use the --mda option to have fetchmail execute a script of your choice for each downloaded message. It can even pass the From and To addresses as parameters to your script if you use %F and %T as placeholders in the command line.

First, create a mailsorter script:

#!/bin/sh

dest_mbox="$1"
from="$2"
to="$3"

case "$from-$to" in
  someone@example.net-myname)
     echo "From $from  `date`" >> "$dest_mbox"
     cat >> "$dest_mbox"
     ;;
  *)
     cat > /dev/null
     ;;
esac

Then run fetchmail -u myname popserver.example.com --mda './mailsorter /tmp/mbox %F %T'

While testing this solution, give fetchmail the --all and --keep flags to make sure that you don't delete your mail accidentally.

Related Question