Skip to content

Instantly share code, notes, and snippets.

@pimpreneil
Last active September 5, 2020 18:44
Show Gist options
  • Save pimpreneil/7163cc8d3f4935cde54a669b00861be6 to your computer and use it in GitHub Desktop.
Save pimpreneil/7163cc8d3f4935cde54a669b00861be6 to your computer and use it in GitHub Desktop.
Fix email maildir timestamps
#!/bin/bash
# Fix emails with bad timestamps in a maildir
# This script reads the date from the email header and set its UNIX timestamp and renames it with the proper date
# e.g. this:
# dec. 05 2017 1512499812.M908995P21566.ip-111-11-11-11,S=16331,W=16746:2,S
# becomes that (the email Date header is "Date: Tue, 22 Oct 2013 10:07:21 +0100"):
# oct. 22 2013 1382432841.M908995P21566.ip-111-11-11-11,S=16331,W=16746:2,S
cd "/var/mail/my@account.org/MyMailDir/cur";
for i in `ls`
do
# We extract the date from the email headers
DATE=$(grep '^Date:' $i | head -1 | cut -d' ' -f1 --complement)
# We compute a touch-compatible timestamp as well as the real timestamp
TOUCHSTAMP=$(date --date="$DATE" +%Y%m%d%H%M)
TIMESTAMP=$(date --date="$DATE" +%s)
# We set the file timestamp
touch -t $TOUCHSTAMP $i
# We rename the file with preprending timestamp
newfilename="$TIMESTAMP.${i#*.}"
mv "$i" "$newfilename"
done
@pimpreneil
Copy link
Author

Fix emails with bad timestamps in a maildir
This script reads the date from the email header and set its UNIX timestamp and renames it with the proper date
e.g. this:
dec. 05 2017 1512499812.M908995P21566.ip-111-11-11-11,S=16331,W=16746:2,S
becomes that (the email Date header is "Date: Tue, 22 Oct 2013 10:07:21 +0100"):
oct. 22 2013 1382432841.M908995P21566.ip-111-11-11-11,S=16331,W=16746:2,S

@phoehnel
Copy link

phoehnel commented Jun 9, 2020

Great! Helped me a lot!

The only thing i added was $(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 5 | head -n 1) at the end of the filename to append a random string. Just for the unlikely event of two mails with the same timestamp.

Credits for the Snippet go to: https://gist.github.com/earthgecko/3089509

@mwodz
Copy link

mwodz commented Sep 5, 2020

The only thing i added was $(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 5 | head -n 1) at the end of the filename to append a random string. Just for the unlikely event of two mails with the same timestamp.

Hmm, that shouldn't be necessary - Maildir spec should provide uniqueness apart from the first part of the filename, which if that was the only part you would be correct..

See https://cr.yp.to/proto/maildir.html under Modern delivery identifiers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment