Help with AppleScript moving email messages

applescriptemailmail.app

I have written the script below to move messages from one mailbox to another in Mail.

But when I run it, just a few email messages are moved at a time. E.g. if I have 10 messages in the mailbox, only three or four are moved. So I have to run the script multiple times to complete the operation! As far as I can tell it's pretty random how many move each time.

So does anyone know why this might be, and how I could improve this script?

Many thanks!

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

tell application "Mail"

    set theWorkInbox to mailbox "Work Inbox" of account "Work"
    repeat with currentWorkMessage in every message of (mailbox "Work Holding Bay" of account "Work")
        set mailbox of currentWorkMessage to theWorkInbox
    end repeat

end tell

I'm using macOS Sierra

Best Answer

It's better if you capture a reference to every message in a variable, instead of getting the reference every time you loop.

tell application "Mail"
    set theWorkInbox to mailbox "Work Inbox" of account "Work"
    set TargetInbox to mailbox "Work Holding Bay" of account "Work"

    -- CAPTURE REFERENCE TO EVERY MESSAGE OF MAILBOX IN A VARIABLE
    set EveryMessage to every message of TargetInbox

    repeat with currentWorkMessage in EveryMessage
        set mailbox of currentWorkMessage to theWorkInbox
    end repeat

end tell