AppleScript for counting messages in Inbox fails with “Can’t get mailbox”

applescriptmail.app

Here is my first attempt at an AppleScript program, which met with ignominious defeat:

tell application "Mail"
    tell mailbox "INBOX"
        count messages
    end tell
end tell

It compiled, but when I ran it, I got the error message

error "Mail got an error: Can’t get mailbox \"INBOX\"." number -1728 from mailbox "INBOX"

Can someone tell me what is wrong, and if there is a short introduction to AppleScript, written for someone used to programming?

Best Answer

Your mistake is understandable in what you expect should be the syntax.

Each account has it's own mailbox named "INBOX"

In Mail the mailbox inbox is the reference to the top level inbox that shows contents of all other inboxes named "INBOX"

2 examples:

Example 1

tell application "Mail"
    set inboxes to first mailbox of every account whose name is "INBOX"
    set messageCount to 0
    repeat with i from 1 to number of items in inboxes

        set this_item to item i of inboxes
        if this_item is not missing value then
            set thisCount to (count of (messages of this_item))
            set messageCount to thisCount + messageCount
            log thisCount
        end if
    end repeat

end tell
log messageCount

Example 2

tell application "Mail"
    set messageCount to (count of (messages of inbox))
end tell

log messageCount

Both return and log the same total.

But example 1 also logs the individual count of each "INBOX"

A good place to start is to read through: AppleScript Fundamentals