Apple script to rename EML files

I do have all my emails exported to a folder with ".eml" format.


I want rename all those files based on "date received" and "sender's email address" info within the EML file. How can I do this?


example: "20171206-123254 - example@domainname.com -.eml"


--

Kindest Regards,

Paulo Guedes

Wednesday, 6 of December, 2017 - 22h:24m [+0000]

MacBook Pro with Retina display, macOS High Sierra (10.13.1)

Posted on Dec 6, 2017 2:29 PM

Reply
Question marked as Top-ranking reply

Posted on Dec 8, 2017 6:48 PM

One final version before I stop fretting at this. If a sender sends you more than one message at exactly the same time (it happened to me with JustGiving), this adds a 2-digit random number to the end of the file name. Plus better handling of no "Mon..." in the date. Plus better use of text item delimiters:



set the_files to (choose fileof type"eml"with prompt"Choose the emails you want to rename:"withmultiple 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 ^\"Date: \" " & the_path)


setAppleScript'stext item delimitersto {"From:"}

set the_sender to text item 2 of the_sender as string


setAppleScript'stext item delimitersto {"Date: ", "("}

set date_string to text item 2 of the_date


try


set ndformat to (do shell script"date -j -f '%a, %d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'")


onerror


try


set ndformat to (do shell script"date -j -f '%d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'")


endtry


endtry

set file_name to ndformat & " " & the_sender & ".eml"


tellapplication"Finder"


activate


try

set name of each_file to file_name

on error number errnum


if errnum = -48then-- identical sender, time & date to a previously processed message results in an identical file name

set the_rand to random number from 10 to 99

set file_name to ndformat & " " & the_sender & the_rand & ".eml"

set name of each_file to file_name


endif


endtry


endtell

endrepeat

45 replies
Question marked as Top-ranking reply

Dec 8, 2017 6:48 PM in response to HD

One final version before I stop fretting at this. If a sender sends you more than one message at exactly the same time (it happened to me with JustGiving), this adds a 2-digit random number to the end of the file name. Plus better handling of no "Mon..." in the date. Plus better use of text item delimiters:



set the_files to (choose fileof type"eml"with prompt"Choose the emails you want to rename:"withmultiple 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 ^\"Date: \" " & the_path)


setAppleScript'stext item delimitersto {"From:"}

set the_sender to text item 2 of the_sender as string


setAppleScript'stext item delimitersto {"Date: ", "("}

set date_string to text item 2 of the_date


try


set ndformat to (do shell script"date -j -f '%a, %d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'")


onerror


try


set ndformat to (do shell script"date -j -f '%d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'")


endtry


endtry

set file_name to ndformat & " " & the_sender & ".eml"


tellapplication"Finder"


activate


try

set name of each_file to file_name

on error number errnum


if errnum = -48then-- identical sender, time & date to a previously processed message results in an identical file name

set the_rand to random number from 10 to 99

set file_name to ndformat & " " & the_sender & the_rand & ".eml"

set name of each_file to file_name


endif


endtry


endtell

endrepeat

Dec 9, 2017 5:48 PM in response to pguedes

Here is a revision and complete AppleScript that does the following:

  1. Prompts for the folder containing the .eml files
  2. Builds a list of all first-level .eml files in that selected folder
  3. Starts a repeat loop on that list
    1. Extracts the Return Path as a string from the content found within the angle brackets. Handles regular, and "folded" Return-Path content.
    2. Extracts the Date string without the optional (TIMEZONE) content
    3. Use the UNIX date command to convert this captured date string into "YYYYmmdd-HHMMSS" format with automatic date/time adjustment to local timezone.
    4. Concatenates the formatted datestring with the captured return path content, adding the ".eml" extension.
    5. Tests if the new filename is longer than 255 characters and displays an alert
    6. Renames the existing .eml file in the selected folder to the new name


This script was tested on El Capitan 10.11.6 against three different .eml files with different Return-Path syntax.


Copy and paste the following (scrollable) AppleScript code into the Script Editor:


--emlname.applescript -- Gets the Return-[Pp]ath content between angle brackets, even if folded to a new line. -- Gets the Date without the trailing (TZ) data -- Builds the start of the new filename by using an automatic timezone adjustment to -- localtime as part of the YYYYmmdd-HHMMSS string. -- Appends the return path string to the reformated date/time string -- Renames original .eml filenames in the chosen folder -- Version 3 (2017-12-09T19:45:20-0500) -- VikingOSX, 2017-12-09, Apple Support Communities property isDesktop : (path to desktop as text) as alias set emlFolder to (choose folder with prompt "Choose a folder containing raw email (.elm) files:" default location isDesktop without invisibles, multiple selections allowed and showing package contents) try tell application "Finder" set eml_list to (every item in folder emlFolder whose kind contains "Email Message" and name extension contains "eml") as alias list end tell if length of eml_list = 0 then return repeat with anItem in eml_list set x to (POSIX path of (anItem as alias))'s quoted form set rpath to (do shell script "perl -0777 -ne 'print \"$1\" if /^Return-[Pp]ath:\\n?\\s*/m;' " & x) set fdate to quoted form of (do shell script "perl -ne 'print \"$1\" if /^Date:\\s*([A-Za-z0-9,+-: ]+)\\s?.*$/;' " & x) set ndformat to (do shell script "date -j -f \"%a, %d %b %Y %X %z\" " & fdate & " +\"%Y%m%d-%H%M%S\"") set newfilename to ndformat & "-" & rpath & ".eml" if length of newfilename > 255 then display alert "Filename exceeds 255 character maximum for filesystem" giving up after 10 end if -- log rpath -- log fdate -- log newfilename -- rename original filename tell application "Finder" to set anItem's name to newfilename end repeat on error errmsg number errnbr my error_handler(errnbr, errmsg) end try return on error_handler(nbr, msg) return display alert "[ " & nbr & " ] " & msg as critical giving up after 10 end error_handler

Dec 11, 2017 3:17 PM in response to pguedes

Spent some more time on this .eml file parsing. Cleaned up, and documented the code. Created decision tree for date parsing format, so only one call to the UNIX date command based on the formatting of the captured date string. Output file name format now:


[YYmmdd-HHMMSS][Original TZ offset if present][Return-Path content].eml


The UNIX date command usage in the script will convert the captured date to your local date-time, so the original timezone offset (e.g. -0500) is unnecessary, and may be confusing in the filename. It is reused it in the filename per your original requirement — if it was present in the captured date content.


The AppleScript was successfully tested on El Capitan 10.11.6 with all security updates, and on macOS Sierra 10.13.2.


Copy and paste the (scrollable) content below into your Script Editor.


--emlname.applescript -- Process exported .eml files from selected folder and construct new filename -- format from captured Return-Path and Date fields. Rename each file to new -- filename construction. Original TZ offset will be omitted if not in Date field: -- [YYYYmmdd-HHMMSS][original TZ offset][contents of return path].eml -- Version 4 (2017-12-11T17:44:00-0500) -- VikingOSX, 2017-12-11, Apple Support Communities property isDesktop : (path to desktop as text) as alias set dow to {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"} -- use pm characters to see if timezone offset is in captured Date string set pm to {"+", "-"} -- Perl regular expressions -- allow for RFC2822 folded return paths if present set rpath_re to "/^Return-[Pp]ath:\\n?\\s*/m;' " -- capture date through +- timezone offset, but exclude trailing (ZONE) if present set fdate_re to "/^Date:\\s*([A-Za-z0-9,+-: ]+)\\s?.*$/;' " -- UNIX BSD Date strftime settings for parsing the captured Date string -- legend: dow = day of week, tz = no time zone, n = no -- Reference: strftime(3) : https://www.freebsd.org/cgi/man.cgi?query=strftime&sektion=3 set date_parse_dow_ntz to quoted form of "%a, %d %b %Y %X " -- Mon, 30 Oct 2017 06:43:23 set date_parse_dow_tz to quoted form of "%a, %d %b %Y %X %z " -- Mon, 30 Oct 2017 06:43:23 -0500 set date_parse_ndow_tz to quoted form of "%d %b %Y %X %z " -- 30 Oct 2017 06:43:23 -0500 set date_parse_ndow_ntz to quoted form of "%d %b %Y %X " -- 30 Oct 2017 06:43:23 set date_format to quoted form of "+[%Y%m%d-%H%M%S]" set emlFolder to (choose folder with prompt "Choose a folder containing raw email (.elm) files:" default location isDesktop without invisibles, multiple selections allowed and showing package contents) try tell application "Finder" set eml_list to (every item in folder emlFolder whose kind contains "Email Message" and name extension contains "eml") as alias list end tell if length of eml_list = 0 then return -- scan body of email looking for return path and Date fields to capture repeat with anItem in eml_list set x to (POSIX path of (anItem as alias))'s quoted form set rpath to (do shell script "perl -0777 -ne 'print \"$1\" if " & rpath_re & x) set fdate to (do shell script "perl -ne 'print \"$1\" if " & fdate_re & x) -- store the original TZ offset in variable pzf for later filename inclusion -- Does this fdate capture have the +- TZ prefix offset? If so, return the -- starting character location in the fdate string. set ispm to (do shell script "ruby -e 'puts ARGV.first =~ /\\+|\\-/' " & fdate's quoted form) as integer -- snap out the timezone offset if it is present if ispm > 0 then set pz to text (ispm + 1) thru -1 of (fdate as text) -- trim leading/trailing white-space of the timezone offset set pzf to do shell script "xargs <<< " & pz else set pzf to "" end if -- we want to convert the output date string with the correct parser -- so make determination in this decision tree. if plus_minus(fdate, pm) and dow contains word 1 of fdate then -- have dow and TZ set parser to date_parse_dow_tz else if plus_minus(fdate, pm) and dow does not contain word 1 of fdate then -- no dow but TZ set parser to date_parse_ndow_tz else if not plus_minus(fdate, pm) and dow contains word 1 of fdate then -- have dow but no TZ set parser to date_parse_dow_ntz else if not plus_minus(fdate, pm) and dow does not contain word 1 of fdate then -- have no dow or Tz set parser to date_parse_ndow_ntz end if -- automatically convert the captured date into users localtime, and output in -- specified formatting. Use try block in case martian date format turns up try set ndformat to (do shell script "date -j -f " & parser & space & fdate's quoted form & space & date_format) on error errmsg number errnbr my error_handler(errnbr, errmsg) return end try if not pzf = "" then set newfilename to ndformat & "[" & pzf & "]" & "[" & rpath & "]" & ".eml" else set newfilename to ndformat & "[" & rpath & "]" & ".eml" end if if length of newfilename > 255 then display alert "Filename exceeds 255 character maximum for filesystem" giving up after 10 end if -- rename original filename to new tell application "Finder" to set anItem's name to newfilename end repeat on error errmsg number errnbr my error_handler(errnbr, errmsg) end try return on plus_minus(adatestr, alist) -- loop through Date string to see if +- characters indicate timezone offset repeat with achar in adatestr if achar is in alist then return true end repeat return false end plus_minus on error_handler(nbr, msg) return display alert "[ " & nbr & " ] " & msg as critical giving up after 10 end error_handler

Dec 9, 2017 11:03 AM in response to pguedes

Yes - read the script and see if you can work out what I've done. These text changes are quite simple and with what I've given you below you might like to try your own variations:



set the_files to (choose fileof type"eml"with prompt"Choose the emails you want to rename:"withmultiple 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)


setAppleScript'stext item delimitersto {"From:"}

set the_sender to text item 2 of the_sender as string


setAppleScript'stext item delimitersto {"<", ">"}

set the_sender to text item 2 of the_sender

set the_sender to "[" & the_sender & "]"


setAppleScript'stext item delimitersto {"Date: ", "("}

set date_string to text item 2 of the_date


try


set ndformat to (do shell script"date -j -f '%a, %d %b %Y %X %z' " & quoted formof date_string & " +'[%Y%m%d-%H%M%S]'")


onerror


try


set ndformat to (do shell script"date -j -f '%d %b %Y %X %z' " & quoted formof date_string & " +'[%Y%m%d-%H%M%S]'")


endtry


endtry

set file_name to ndformat & " " & the_sender & ".eml"


tellapplication"Finder"


activate


try

set name of each_file to file_name

on error number errnum


if errnum = -48then-- identical time & date

set the_rand to random number from 10 to 99

set file_name to ndformat & the_sender & the_rand & ".eml"

set name of each_file to file_name


endif


endtry


endtell

endrepeat

Dec 13, 2017 9:35 AM in response to pguedes

It turns out that the Apple hosting software was removing a critical piece of the Return-Path regular expression when the AppleScript source was posted. In my testing, this simply omits finding the Return path content, but does not introduce any other AppleScript runtime issues, including those involving the Finder.


Here is version 6. It introduces HTML angle brackets in the rpath regular expression to prevent the JIVE hosting software from malicious regular expression syntax removal.


I copied this posted code back into the macOS 10.13.2 Script Editor, and when run against the test .eml files, the proper format was applied in the renaming process, and there were no runtime errors.


--emlname.applescript -- Process exported .eml files from selected folder and construct new filename -- format from captured Return-Path and Date fields. Rename each file to new -- filename construction. Original TZ offset will be omitted if not in Date field: -- [YYYYmmdd-HHMMSS][original TZ offset][contents of return path].eml -- Version 6, Added HTML angle bracket names to rpath RE string. Prevents Apple host regex removal. -- Tested: OS X 10.11.6, macOS 10.13.2. -- VikingOSX, 2017-12-12, Apple Support Communities property isDesktop : (path to desktop as text) as alias set dow to {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"} -- use pm characters to see if timezone offset is in captured Date string set pm to {"+", "-"} -- Perl regular expressions -- allow for RFC2822 (multiple) folded return paths if present set rpath_re to " /^Return-[Pp]ath:\\R?\\s*<(.*?)>/ms;' -ne '$val = $1;$val =~ s/\\R\\s*?//g;print \"$val\";' " -- capture date through +- timezone offset, but exclude trailing (ZONE) if present set fdate_re to "/^Date:\\s*([A-Za-z0-9,+-: ]+)\\s?.*$/;' " -- UNIX BSD Date strftime settings for parsing the captured Date string -- legend: dow = day of week, tz = time zone, n = no -- Reference: strftime(3) : https://www.freebsd.org/cgi/man.cgi?query=strftime&sektion=3 set date_parse_dow_ntz to quoted form of "%a, %d %b %Y %X " -- Mon, 30 Oct 2017 06:43:23 set date_parse_dow_tz to quoted form of "%a, %d %b %Y %X %z " -- Mon, 30 Oct 2017 06:43:23 -0500 set date_parse_ndow_tz to quoted form of "%d %b %Y %X %z " -- 30 Oct 2017 06:43:23 -0500 set date_parse_ndow_ntz to quoted form of "%d %b %Y %X " -- 30 Oct 2017 06:43:23 set date_format to quoted form of "+[%Y%m%d-%H%M%S]" set emlFolder to (choose folder with prompt "Choose a folder containing raw email (.elm) files:" default location isDesktop without invisibles, multiple selections allowed and showing package contents) try tell application "Finder" set eml_list to (every item in folder emlFolder whose kind contains "Email Message" and name extension contains "eml") as alias list end tell if length of eml_list = 0 then return -- scan body of email looking for return path and Date fields to capture repeat with anItem in eml_list set x to (POSIX path of (anItem as alias))'s quoted form set rpath to (do shell script "perl -0777 -ne '$_ =~ " & rpath_re & x) set fdate to (do shell script "perl -ne 'print \"$1\" if " & fdate_re & x) -- store the original TZ offset in variable pzf for later filename inclusion -- Does this fdate capture have the +- TZ prefix offset? If so, return the -- starting character location in the fdate string. set ispm to (do shell script "ruby -e 'puts ARGV.first =~ /\\+|\\-/' " & fdate's quoted form) as integer -- snap out the timezone offset if it is present if ispm > 0 then set pz to text (ispm + 1) thru -1 of (fdate as text) -- trim leading/trailing white-space of the timezone offset set pzf to do shell script "xargs <<< " & pz else set pzf to "" end if -- we want to convert the output date string with the correct parser -- so make determination in this decision tree. if plus_minus(fdate, pm) and dow contains word 1 of fdate then -- have dow and TZ set parser to date_parse_dow_tz else if plus_minus(fdate, pm) and dow does not contain word 1 of fdate then -- no dow but TZ set parser to date_parse_ndow_tz else if not plus_minus(fdate, pm) and dow contains word 1 of fdate then -- have dow but no TZ set parser to date_parse_dow_ntz else if not plus_minus(fdate, pm) and dow does not contain word 1 of fdate then -- have no dow or Tz set parser to date_parse_ndow_ntz end if -- automatically convert the captured date into users localtime, and output in -- specified formatting. Use try block in case martian date format turns up set ndformat to (do shell script "date -j -f " & parser & space & fdate's quoted form & space & date_format) set RP to "" -- return path if not rpath = "" then set RP to "[" & rpath & "]" end if set TZOFFSET to "" -- TZ offset if any if not pzf = "" then set TZOFFSET to "[" & pzf & "]" end if set newfilename to ndformat & TZOFFSET & RP & ".eml" if length of newfilename > 255 then display alert "Filename exceeds 255 character maximum for filesystem" giving up after 10 end if -- rename original filename to new -- log (emlFolder & newfilename) as text as alias tell application "Finder" if not (exists item ((emlFolder as text) & newfilename)) = true then set anItem's name to newfilename end if end tell end repeat on error errmsg number errnbr my error_handler(errnbr, errmsg) end try return on plus_minus(adatestr, alist) -- loop through Date string to see if +- characters indicate timezone offset repeat with achar in adatestr if achar is in alist then return true end repeat return false end plus_minus on error_handler(nbr, msg) return display alert "[ " & nbr & " ] " & msg as critical giving up after 10 end error_handler

Dec 8, 2017 5:39 PM in response to VikingOSX

Well I've got round mail servers that fold Return-path: for no apparent reason. And I've got round mail servers that omit "Mon, " (etc) from Date:


And I've repunctuated VikingOSX's nifty date command so it works in the context of my AppleScript:


set the_files to (choose fileof type"eml"with prompt"Choose the emails you want to rename:"withmultiple 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 -i \"Return-path:\" " & the_path)

set the_date to (do shell script "grep -i \"Date: \" " & the_path)


setAppleScript'stext item delimitersto {"<", ">"}

if (count text items of the_sender) = 1 then

set the_sender to paragraph 2 of (read each_file)

set the_sender to text item 2 of the_sender


else

set the_sender to text item 2 of the_sender


endif


setAppleScript'stext item delimitersto"Date: "

set date_string to text item 2 of the_date


setAppleScript'stext item delimitersto" ("

set date_string to text item 1 of date_string

log date_string


try


set ndformat to (do shell script"date -j -f '%a, %d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'") -- with thanks to VikingOSX


endtry


try


set ndformat to (do shell script"date -j -f '%d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'") -- with further thanks to VikingOSX


endtry

set file_name to ndformat & " " & the_sender & "-.eml"


tellapplication"Finder"


activate

set name of each_file to file_name


endtell

endrepeat


And it has renamed 90+ .eml files in one pass without error, in just a few seconds.


But that doesn't solve the error the OP found when he ran the script, and it doesn't anticipate any other crud that a differently configured mail server is going to turn up.


It works for me, but it may not work for anyone else...


EDIT: (And I think using From: rather than Return-path: may be a better solution...)


H

Dec 8, 2017 6:15 PM in response to HD

This is an improvement:


set the_files to (choose fileof type"eml"with prompt"Choose the emails you want to rename:"withmultiple 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 -i ^\"From: \" " & the_path)

set the_date to (do shell script "grep -i ^\"Date: \" " & the_path)


setAppleScript'stext item delimitersto"From:"

set the_sender to text item 2 of the_sender


setAppleScript'stext item delimitersto"Date: "

set date_string to text item 2 of the_date


setAppleScript'stext item delimitersto" ("

set date_string to text item 1 of date_string


try


set ndformat to (do shell script"date -j -f '%a, %d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'") --thanks VikingOSX


onerror -- maybe no "Mon..." in the date


try


set ndformat to (do shell script"date -j -f '%d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'")


endtry


endtry

set file_name to ndformat & " " & the_sender & "xyxy.eml"


tellapplication"Finder"


activate

set name of each_file to file_name


endtell

endrepeat

Dec 9, 2017 10:05 AM in response to pguedes

Hi Paulo,


The email address is relatively straightforward:



set the_files to (choose fileof type"eml"with prompt"Choose the emails you want to rename:"withmultiple 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)


setAppleScript'stext item delimitersto {"From:"}

set the_sender to text item 2 of the_sender as string


setAppleScript'stext item delimitersto {"<", ">"}

set the_sender to text item 2 of the_sender


setAppleScript'stext item delimitersto {"Date: ", "("}

set date_string to text item 2 of the_date


try


set ndformat to (do shell script"date -j -f '%a, %d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'")


onerror


try


set ndformat to (do shell script"date -j -f '%d %b %Y %X %z' " & quoted formof date_string & " +'%Y%m%d - %H%M%S'")


endtry


endtry

set file_name to ndformat & " " & the_sender & ".eml"


tellapplication"Finder"


activate


try

set name of each_file to file_name

on error number errnum


if errnum = -48then-- identical time & date

set the_rand to random number from 10 to 99

set file_name to ndformat & " " & the_sender & the_rand & ".eml"

set name of each_file to file_name


endif


endtry


endtell

endrepeat


Not sure how to deal with the date - I'll have to investigate.


Cheers,


H

Dec 9, 2017 1:05 PM in response to pguedes

Depending on the mail agent, there can be a "Return-path:" or "Return-Path:" string in the .eml file. I have now allowed for that. Additionally, although the Date format in the .eml is standard, it can appear with, or without a trailing parenthetical time zone. I cleaned up the regular expression for Date and it appears to work correctly with my test documents.


Try this. Longer lines have wrapped.


set foobar to read (choose fileof type "eml" with prompt "Choose an eml file:" without multiple selections allowed)


set captures to paragraphs of (do shell script "perl -ne 'print \"$1\\n$2\" if /^Return-[Pp]ath:\\s<(.*?)>.*|^Date:\\s([A-Za-z0-9,+-: ]+)\\s?.*/;' <<<" & foobar's quoted form)

logcaptures

set ndformat to (do shell script "date -j -f \"%a, %d %b %Y %X %z\" " & (last item of captures)'s quoted form & " +\"%Y%m%d-%H%M%S\"")


set newfilename to ndformat & "-" & (first item of captures) & ".eml"

lognewfilename

return

Dec 7, 2017 10:38 AM in response to pguedes

Hi Paulo


Try the script below on a two or three .eml files. There may be localisation issues, especially with the date, but it works for me on a UK English system:



set the_files to (choose fileof type"eml"with prompt"Choose the emails you want to rename:"withmultiple 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 -i \"Return-path:\" " & the_path)

set the_date to (do shell script "grep -i \"Date: \" " & the_path)


setAppleScript'stext item delimitersto {"<", ">"}

set the_sender to text item 2 of the_sender


setAppleScript'stext item delimitersto" "

set date_string to word 5 of the_date & word 4 of the_date & word 3 of the_date as string


setAppleScript'stext item delimitersto":"

set time_string to word -1 of text item 2 of the_date & text item 3 of the_date & word 1 of text item 4 of the_date as string

set file_name to date_string & "-" & time_string & " " & the_sender & "-.eml"

tell application "Finder" to set name of each_file to file_name

endrepeat


I'm sure I could have been cleverer with the parsing but I don't really speak grep.


It will ask you to choose .eml files and on my system, it renames them in the form


2017Dec06-171530 sender@domain.com-.eml


(Turning "Dec" into "12" - etc - remains to be done).


Let us know what happens...


H


EDIT: made the two grep commands case insensitive.

Dec 7, 2017 2:20 PM in response to HD

I have an email here that has a Date string of: Date: Fri, 01 Dec 2017 07:18:55 -0800 (PST).


If I capture just Fri, 01 Dec 2017 07:18:55 -0800


I can use it in a macOS date command as follows to automatically adjust the -0800 (PST) to local (EST) time, and output the desired datetime format that the OP requested. Had the time been 15:18:55 -0000 (GMT), the following command would have still returned the 10:18:55 EST local time.The command string below wraps.


set ndformat to do shell script "date -j -f \"%a, %d %b %Y %X %z\" \"Fri, 01 Dec 2017 07:18:55 -0800\" +\"%Y%m%d - %H%M%S\""

logndformat

Result:

"20171201 - 101855"


See FreeBSD strftime(3) for reference.

Dec 12, 2017 5:05 AM in response to pguedes

The -48 error code is a file rename error because you are attempting to rename to a file that already exists. When I tested, once I had renamed to the new format, before the next test, I removed the new format filenames, and replaced them with the original .eml items. I suppose I could put a guard clause around the rename section of the code to prevent this error if the new filename format already exists.


As for the blank Return-Path capture, try changing the following. In Perl, the \R (\\R for AppleScript) looks for any form of line ending, and in the case of RFC2822 Mail standard, the CRLF pair used in Return-Path "folding."


From:


set rpath_re to "/^Return-[Pp]ath:\\n?\\s*<(.*?)>/m;' "


to:


set rpath_re to "/^Return-[Pp]ath:\\R?\\s*<(.*?)>/m;' "


Run it against the specific .eml that was producing the blank content from the Return-Path, and see if this change fixes it.

Dec 10, 2017 12:20 PM in response to pguedes

HD and I were operating off of the original premise that you had already exported the emails into their raw .eml format, and you were requesting content extraction and reformatting from those existing files. Regular Expressions are more powerful and adaptable at data extraction than AppleScript — but more resource intensive at the readability/understanding/testing level. Whether AppleScript or Regular Expressions, data that can change based on what email system touched it can require alot more coding to handle the exceptions.


Yes, an AppleScript could loop through a group of selected messages and extract/reformat the data before saving the raw message .eml files. Although the Mail scripting definitions have message properties for date received, and reply to, there is no Return-Path property. You would still have to access the all headers message property content, and parse that for Return-Path — and this could balloon the AppleScript code without the power of regular expressions.


Whereas the UNIX date command can automatically convert a date received into a locatime time string — in one line, AppleScript will not do that for you, and will require more AppleScript date/time coding effort.


Did you modify my Version 3 script to use HD's contributed UNIX date solution for Dates that have, or do not have the day of the week in them? Seems like that was an outstanding item.

Dec 6, 2017 4:25 PM in response to pguedes

What happens if you open that folder in a Finder Window, select list view, and then press command+J to show view options. Set Arrange by to None, and Sort by to Name. The first part of the filename that represents a date string will automatically sort in ascending date order, and the rest of the filename will have no choice but to tag along.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Apple script to rename EML files

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.