Search code examples
macosemailapplescriptpurgerecycle-bin

Applescript Purge Email Older than 2 Days


I am new to Applescript. I have one specific email account that exists solely for the purpose receiving error reports with an attached image. The mailbox can fill up quickly.

I'd like to be able to run a script that will delete mail older than two days, so I tried my hand at the following script.

I'd like to correct what I have written so I can learn from my mistakes rather that use a different method. Looking for some constructive criticism:

set daysToPreserve to 2

tell application "Mail"
activate
set mailboxList to mailbox "INBOX" of account “MyAccount"
repeat with theCurrentMailbox in mailboxList
    set emailList to (every message of (mailbox theCurrentMailbox of account “MyAccount") whose date received is less than or equal to ((current date) - daysToPreserve * days))
    if (count mailboxList) is greater than 0 then
        move mailboxList to mailbox "Trash" of account “MyAccount"
    end if
end repeat
end tell

display dialog "Old Mail Messages Have Been Purged" buttons ["OK"]

Solution

  • You put 1 item into a repeat block with this:

    set mailboxList to mailbox "INBOX" of account “MyAccount"
    repeat with theCurrentMailbox in mailboxList
    

    You can try something like this:

    set daysToPreserve to 2
    set myAcount to "MyAccount"
    set dateReference to (current date) - (daysToPreserve * days)
    
    tell application "Mail"
        activate
        set myMailbox to mailbox "INBOX" of account myAcount
        set accountTrash to mailbox "Trash" of account myAcount
        set messagesToDelete to messages of myMailbox whose date received ≤ dateReference
        repeat with aMessage in messagesToDelete
            move aMessage to accountTrash
        end repeat
    end tell
    
    display dialog (count messagesToDelete) & " old Mail Messages Have Been Purged" as text buttons ["OK"]