I have an AppleScript that does the following.
- Activates Mail.app.
- Looks for messages in a particular folder that is not flagged (“OmniFocus”, in my usage).
- Runs a script on those messages to add them as tasks in Omnifocus.
- Flags each message.
- Moves each message to an archive folder.
I added the flagging step (Step 4) because without it, the script was finding the same messages repeatedly even though they had already been moved to the Archive folder. This resulted in many duplicate tasks in OmniFocus. The script works, but the use of the flagged status is a hack and I’d like to understand why AppleScript keeps finding messages in my “OmniFocus” folder when they’ve already been moved to the “Archive” folder.
I’d really appreciate any suggestions - I’d love to remove the flagging step. Script is below.
property theAccount : "FastMail"
on run
tell application "Mail"
launch
synchronize with account theAccount
set theOFFolder to mailbox "OmniFocus" in account theAccount
set theArchiveFolder to mailbox "Archive" in account theAccount
set theTempMessages to {}
set theMessages to {}
set theTempMessages to the messages in theOFFolder
-- Remove the message from the list if it is flagged
repeat with aMessage in theTempMessages
if the flagged status of aMessage is false then
set the end of theMessages to aMessage
end if
end repeat
-- Quit if there are no messages to process
set theMessageCount to count of theMessages
if theMessageCount is equal to 0 then
tell me to quit
end if
-- For each message, add it to Omnifocus, flag it, then move it to the FastMail archive folder
try
repeat with aMessage in theMessages
my process_message(aMessage)
delay 1
end repeat
on error m number n
tell application "OmniFocus"
log "Exception in Mail action: (" & n & ") " & m
end tell
end try
repeat with aMessage in theMessages
tell application "Mail"
set flagged status of aMessage to true
move aMessage to theArchiveFolder
end tell
end repeat
end tell
try
tell application "OmniFocus"
synchronize default document
end tell
end try
tell application "Mail"
synchronize with account theAccount
end tell
end run
on process_message(theMessage)
using terms from application "Mail"
set theSubject to subject of theMessage
set singleTask to false
if (theSubject starts with "Fwd: ") then
-- Whole forwarded messages shouldn't split.
set singleTask to true
set theSubject to rich text 6 through -1 of theSubject
end if
set theText to "--" & theSubject & return & "message:%3c" & message id of theMessage & "%3e" & return & content of theMessage
tell application "OmniFocus"
tell default document
parse tasks with transport text theText as single task singleTask
end tell
end tell
end using terms from
end process_message
Model: iMac 2011
AppleScript: 2.2.4
Browser: Safari 536.29.13
Operating System: Mac OS X (10.8)