Thursday, October 26, 2017

Run all Airmail rules

I currently use Airmail as my Mac (and iOS) mail client. With many email accounts I found that Airmail fits my needs OK. And I have created a large number of rules that is automatically performed on new emails in my inbox. However, for different reasons I would sometimes like to perform all my rules manually. As far as I know this is not possible in the Mac version of Airmail. So I had to implement it myself using AppleScript. You can find the program below. A few things you should be aware of: (i) This program do not open the Airmail application (I expect Airmail to be in use on your Mac). (ii) The program needs to be able to control your computer (see System Preferences → Security & Privacy → Privacy → Accessibility). (iii) I have tried to make it robust, but no guarantees. It could mess up.

I suggest to save this code as the application RunAllAirmailRules.app in the Applications folder of your home directory (choose File Format → Application in the save dialog in Script Editor). Enjoy.

-- An Airmail 3 application
tell application "System Events" to tell process "Airmail 3"
  set frontmost to true
  
  -- Activate (and open) "Rules" window of Airmail 3
  set rules to windows where title contains "Rules"
  if rules is {} then
    click menu item "Rules" of menu "Window" of menu bar 1
    delay 1
    set rules to windows where title contains "Rules"
  end if
  if rules is not {} then
    perform action "AXRaise" of item 1 of rules
    
    -- Traverese all rules
    set all_rules to rows of table 1 of scroll area 1 of item 1 of rules
    repeat with rule in all_rules
      
      -- Select rule and go to preview of the rule
      set the value of attribute "AXSelected" of rule to true
      set enabled_rule to the value of checkbox "Enable" of item 1 of rules as boolean
      if enabled_rule then
        click button "Preview" of item 1 of rules
        
        -- Click "Apply to ..." button
        set btn_ok to false
        repeat while not btn_ok
          try
            set btn to button "Apply to previous messages" of sheet 1 of window "Rules"
            if enabled of btn then
              set btn_ok to true
            end if
          on error msg
            delay 0.1
            set btn_ok to false
          end try
        end repeat
        click btn
        
        -- Click "Close" button
        set btn_ok to false
        repeat while not btn_ok
          try
            set btn to button "Close" of sheet 1 of window "Rules"
            if enabled of btn then
              set btn_ok to true
            end if
          on error msg
            delay 0.1
            set btn_ok to false
          end try
        end repeat
        click btn
        
      end if
    end repeat
  end if
end tell

No comments: