Apple Mail - Discard Spam

Summary: Completely deletes the messages in the Spam mailbox.
Requires: SpamSieve, Apple Mail
Install Location: ~/Library/Scripts/Applications/Mail

Description

Running this script from the Scripts menu will completely delete all the messages in the Spam mailbox under “On My Mac” (rather than putting them in the trash, which is what happens when you press the Delete key).

Download in Compiled Format · Download in Text Format

Script

on run {}
    
tell application "Mail"
        
set _messages to messages of my spamMailbox()
        
my completelyDeleteMessages(_messages)
    
end tell
end run

on spamMailbox()
    
tell application "SpamSieve"
        
set {_spamFolderName, _isLocal} to lookup keys {"AppleMailTrainSpamName", "AppleMailLocalSpamMailbox"} default values {"Spam", true}
    
end tell
    
tell application "Mail"
        
if _isLocal then return mailbox _spamFolderName
        
set _accounts to accounts
        
repeat with _account in accounts
            
try
                
return mailbox _spamFolderName of _account
            
end try
        
end repeat
        
error "No spam mailbox named “" & _spamMailboxName & "” found."
    
end tell
end spamMailbox

on completelyDeleteMessages(_messages)
    
tell application "Mail"
        
-- Build up list because "messages of trash mailbox" is very slow; we only want to call it once.
        
set _messageIDs to {}
        
repeat with _message in _messages
            
-- "message id" is not unique, but "id" changes when the message is moved.
            
copy _message's message id to end of _messageIDs
            
delete _message
        
end repeat
        
set _trashedMessages to messages of trash mailbox -- Includes contents of child mailboxes.
        
repeat with _trashedMessage in _trashedMessages
            
try
                
if _trashedMessage's message id is in _messageIDs then delete _trashedMessage
            
on error
                
-- Sometimes Mail reports an error getting "_trashedMessage's message id", saying it can't find the message.
            
end try
        
end repeat
    
end tell
end completelyDeleteMessages

Last Modified: 2014-04-25

Running the Script

You can use AppleScript Editor (AppleScript Utility prior to Mac OS X 10.6) to enable Mac OS X’s built-in Script menu. Download the compiled script file and install it in the Install Location recommended above, creating any necessary folders. To run the script, just select it from the menu. FastScripts provides a similar menu that supports keyboard shortcuts and other features.