Here you go - with some amendments to catch email addresses not enclosed in diamond brackets.
set the_files to (choose file of type "eml" with prompt "Choose the emails you want to rename:" with multiple selections allowed)
repeat with each_file in the_files
set the_path to quoted form of POSIX path of each_file
set the_sender to (do shell script "grep ^\"From: \" " & the_path)
set the_date to (do shell script "grep -i ^\"Date: \" " & the_path)
set AppleScript's text item delimiters to {"From: "}
set the_sender to text item 2 of the_sender as string
set AppleScript's text item delimiters to {"<", ">"}
try
set the_sender to text item 2 of the_sender
on error
set AppleScript's text item delimiters to "From: "
set the_sender to text item 1 of the_sender
end try
set the_sender to "[" & the_sender & "]"
set AppleScript's text item delimiters to {"Date: ", "("}
set date_string to text item 2 of the_date
set time_diff to "[" & (text -5 thru -1 of date_string) & "]"
try
set ndformat to (do shell script "date -j -f '%a, %d %b %Y %X %z' " & quoted form of date_string & " +'[%Y%m%d-%H%M%S]'")
on error
try
set ndformat to (do shell script "date -j -f '%d %b %Y %X %z' " & quoted form of date_string & " +'[%Y%m%d-%H%M%S]'")
end try
end try
set file_name to ndformat & time_diff & the_sender & ".eml"
tell application "Finder"
activate
try
set name of each_file to file_name
on error number errnum
if errnum = -48 then -- identical time & date
set the_rand to random number from 10 to 99
set file_name to ndformat & time_diff & the_sender & the_rand & ".eml"
set name of each_file to file_name
end if
end try
end tell
end repeat
I'm still finding occasional oddities - including email addresses not enclosed in diamond bracket characters in the From: header. I've run it on 170 .eml files. It may well throw errors if it finds different configurations/misconfigurations in the headers. The
I have run it successfully on 170 .eml files. There may still be odd configurations in email headers that will cause it to throw errors, or return inconsistencies in the time zones.