I want to find an email in the Mail app by its Message-ID and display it in the preview pane, but I haven’t been able to select the correct message.
It always selects the next message instead of the intended one. Why is this happening?
tell application "Mail"
activate
set targetMessage to missing value
set targetMailbox to missing value
set MessageID to "id"
repeat with anAccount in accounts
repeat with aBox in mailboxes of anAccount
try
set msgList to (messages of aBox whose message id is MessageID)
if (count of msgList) > 0 then
set latestMessage to item 1 of msgList
repeat with msg in msgList
if date received of msg > date received of latestMessage then
set latestMessage to msg
end if
end repeat
set targetMessage to latestMessage
set targetMailbox to aBox
exit repeat
end if
end try
if targetMessage is not missing value then exit repeat
end repeat
if targetMessage is not missing value then exit repeat
end repeat
if targetMessage is not missing value then
set viewerCount to count of message viewers
if viewerCount > 0 then
set selected mailboxes of message viewer 1 to {targetMailbox}
delay 1
set selected messages of message viewer 1 to {targetMessage}
delay 1
activate
return "Found"
else
set newViewer to make new viewer with properties {selected mailboxes:{targetMailbox}}
delay 1
set selected messages of newViewer to {targetMessage}
delay 1
activate
return "Found"
end if
else
return "Not Found"
end if
end tell