Zantafio
Zantafio

Reputation: 567

how to delete a mail mailbox with Applescript

I want my script to traverse a tree of mailboxes and delete empty mailboxes:

tell application "Mail"
    my cleanup(mailbox "Archives")
end tell

on cleanup(box)
    tell application "Mail"

    if (count of mailboxes of box) > 0 then
        repeat with mbx in mailboxes of box

            my cleanup(mbx)
        end repeat
    else
        if (count of messages of box) = 0 then delete box
    end if


    end tell
end cleanup

The "delete box" causes error: error "Mail got an error: Can’t get item 1 of every mailbox of item 1 of every mailbox of mailbox \"Archives\"." number -1728 from item 1 of every mailbox of item 1 of every mailbox of mailbox "Archives"

Upvotes: 1

Views: 565

Answers (1)

vadian
vadian

Reputation: 285270

There are two issues:

• The index variable mbx in the line

repeat with mbx in mailboxes of box

is a reference like item 1 of every mailbox of box rather than mailbox "something" of box. You have to dereference the variable before passing it to the handler with contents of.

• In the same line you'll get an error if for example item 1 has been deleted, item 2 is now item 1 and there is no item 2 anymore. To avoid this use the keyword get to retrieve a copied reference which isn't affected by deletions during the loops.

tell application "Mail"
    my cleanup(mailbox "Archives")
end tell

on cleanup(box)
    tell application "Mail"

        if (count of mailboxes of box) > 0 then
            repeat with mbx in (get mailboxes of box)

                my cleanup(contents of mbx)
            end repeat
        else
            if (count of messages of box) = 0 then delete box
        end if

    end tell
end cleanup

Upvotes: 1

Related Questions