Based on the various scripts for importing e-mail attachments floating around the forum (e.g. importing emails with attached PDF files - #10 by Blanc) I’ve created a script that can do the following:
- Separate attachments from e-mails (.eml files)
- Add attachments and original e-mail to a new group
- Add a backlink (x-devonthink-item://) to the attachments referring to the original e-mail
- Update the timestamps of the group and attachments based on the original e-mail
The script uses large timeouts to also make it usable on larger e-mail archives.
-- Import attachments of selected emails
tell application id "DNtp"
set theSelection to the selection
set tmpFolder to path to temporary items
set tmpPath to POSIX path of tmpFolder
with timeout of 14400 seconds
repeat with theRecord in theSelection
if type of theRecord is unknown and path of theRecord ends with ".eml" then
set theRTF to convert record theRecord to rich
set theURL to reference URL of theRecord
set newGroup to false
try
if type of theRTF is rtfd then
set thePath to path of theRTF
set theGroup to parent 1 of theRecord
set theName to name of theRecord
set theModificationDate to the modification date of theRecord
set theCreationDate to the creation date of theRecord
set theAdditionDate to the addition date of theRecord
tell text of theRTF
if exists attachment in attribute runs then
tell application "Finder"
set filelist to every file in ((POSIX file thePath) as alias)
repeat with theFile in filelist
set theAttachment to POSIX path of (theFile as string)
if theAttachment does not end with ".rtf" and theAttachment does not end with ".png" then
try
with timeout of 7200 seconds
-- Importing skips files inside the database package,
-- therefore let's move them to a temporary folder first
set theAttachment to move ((POSIX file theAttachment) as alias) to tmpFolder with replacing
set theAttachment to POSIX path of (theAttachment as string)
tell application id "DNtp"
if newGroup is false then
set newGroup to create record with {name:theName, type:group, modification date:theModificationDate, creation date:theCreationDate, addition date:theAdditionDate} in theGroup
end if
set importedFile to import theAttachment to newGroup
set URL of importedFile to theURL
set the modification date of importedFile to theModificationDate
set the creation date of importedFile to theCreationDate
set the addition date of importFile to theAdditionDate
end tell
end timeout
end try
end if
end repeat
end tell
if newGroup is not false then
tell application id "DNtp"
move record theRecord to newGroup
end tell
end if
end if
end tell
end if
on error msg
display dialog msg
end try
end if
delete record theRTF
end repeat
end timeout
end tell
on makeDate(dateString)
set theDate to date dateString
end makeDate