A Deep Dive Into Filing Mail Messages Using AppleScript

There are a number of techniques I am looking into to file messages into macOS Mail mailboxes using AppleScript for the macOS Sonoma version of MsgFiler, but each possible solution has its own set of drawbacks and limitations. Let’s dive into each one, but first some background on how MsgFiler with the Engine used to work in macOS Ventura and earlier:

MsgFiler + Engine

In macOS Ventura and before, the Engine Mail Plug-in has direct access to Mail’s internal functions. As a result, all MsgFiler had to do was call this method:

[messageViewer transferSelectedMessagesToMailbox:mailbox moveMessages:YES];

So simple and easy. Sadly, macOS Sonoma removed the ability to install and run Mail Plug-ins, so here we are.

Via the Antiquated Mail Dictionary

The AppleScript dictionary for the Mail application reveals a number of ways to file a message. Consider the following example:

  • Mailbox account is Gmail
  • Destination mailbox is called “Test”

Here is a sample AppleScript that shows the different ways to file the currently selected message or messages:

set theMessages to get selection 
set theMailbox to mailbox "Test" in account "gmail.com"

repeat with theMessage in theMessages
set mailbox of theMessage to theMailbox

-- Or
move theMessage to theMailbox
end repeat

Normally, I would use the set command on the mailbox property of a message. The problem happens when the account of the message being filed is Gmail. Gmail’s IMAP implementation is non-standard in how it handles labels and mailboxes. When you apply a label to a message, you’re not moving it to a separate folder; you’re tagging it with that label.

In macOS Mail, manually moving a message from the inbox of a Gmail account removes the Inbox label and applies the label of the destination mailbox. This also happens when you use the Move to menu under the Message menu.

When moving messages using AppleScript, however, the Inbox label is not removed from the moved message. As a result, the message looks like it has been duplicated. It appears both in the Inbox and in the destination mailbox. In order to remove the message from the Inbox, one needs to archive it. You can accomplish this by using the AppleScript Accessibility API as follows:

tell application "Mail" to activate
tell application "System Events"
tell menu bar 1 of application process "Mail"
tell menu bar item 7 -- Message
tell menu 1
tell menu 19 -- Archive
if enabled then
click
end if
end tell
end tell
end tell
end tell
end tell

Now, if the account of the message is not Gmail, calling the set mailbox command will automatically remove the message from the Message Viewer. What it won’t do, however, is select the next message in the Message Viewer. The selection disappears, forcing you to use the mouse or trackpad to select the next message to file. One can get around this by sending the down arrow key code to the Mac:

tell application "System Events" to key code 125

Putting it all together, one can create a script that takes a mailbox path and files it, optionally selecting the next message or archiving the message is it’s from Gmail:

tell application "Mail"
set theMessages to get selection
set theMailbox to mailbox "Test" in account "gmail.com"
set toArchive to false

repeat with theMessage in theMessages
set mailbox of theMessage to theMailbox

if account of theMessage contains "gmail" then
set toArchive to true
end if

if toArchive is false then
tell application "System Events" to key code 125
end if
end repeat

if toArchive then
tell application "System Events"
tell menu item 19 of menu 1 of menu bar item 7 of menu bar 1 of application process "Mail"
if enabled then
click
end if
end tell
end tell
end if
end tell

Now there’s a problem with this approach and that’s if multiple messages are selected that belong to different mail accounts. It’s possible that the selection will change by applying the arrow down key code to Mail. This could cause the wrong message to be archived and keep duplicate emails in the Inbox.

This is roughly the approach that Ike Nassi’s Keyboard Maestro macros uses to file messages.

Using the Move to Menu

This has led to be to investigating whether it’s possible to use the Message > Move to menu item to file messages. This approach has the benefit of using Apple’s built-in methods for filing messages instead of its aging and out-of-date AppleScript method. When you use the Move to menu, it’s just like dragging and dropping the message into a mailbox.

In its simplest form, we take the path to the mailbox and locate the correct mailbox in the menu. When the mailbox hierarchy is completely collapsed, items in the Move to menu match what you would expect:

  • Message
    • Move to
      • Gmail.com
        • Archive
        • Sent
        • Trash
        • Junk
        • Test

It’s relatively simple to locate the mailbox by traversing the menu item hierarchy:

tell application "Mail" to activate

tell application "System Events"
tell menu bar 1 of application process "Mail"
tell menu item "Test" of menu 1 of menu item "Gmail.com" of menu 1 of menu item 21 of menu 1 of menu bar item 7
click
end tell
end tell
end tell

Targeting a Folder with Children

What if you wanted to file messages to a folder that contained mailboxes:

  • Gmail.com
    •  Finances
      • Bills
      • Orders

Tell AppleScript to click on the Finances folder doesn’t do what you would expect. It displays the Finances menu, but selects the first child, Bills. The solution is to use System Events to simulate the Left Arrow key, followed by pressing Return:

tell application "System Events"
click at {x, y}
delay 0.1
key code 123
delay 0.1
keystroke return end tell

Where x and y are the coordinates of the destination menu (i.e. Finances). Fortunately, the position of the menu is provided to AppleScript.

Expanding Hierarchy Problems

Now, what happens if the mailbox hierarchy was expanded? The Move to menu changes to reflect the expanded hierarchy. The way Apple does this, however, leaves much ambiguity for AppleScript as to the correct position of a mailbox.

  • Message
    • Move to
      • Gmail.com
      •  Test

See the difference? Test is on the same level as its account Gmail.com. AppleScript, given the Test menu item, can’t easily determine if it’s part of Gmail.com or a different account. This becomes extremely complicated if you have multiple mailboxes with the same name. Consider this:

  • Message
    • Move to
      • iCloud
      •  Test
      • Gmail.com
      •  Test

You can no longer use the script above because iCloud and Gmail.com are expanded so there is nothing to be found in their list of menu items (it returns 0). If those two accounts were collapsed, we could find the correct Test mailbox. As it stands, both Test mailboxes could easily be the one chosen, which is not good. And, if you have more mailboxes with the same name, it gets even more complicated!

  • Message
    • Move to
      • Gmail.com
      •  Misc
      •   Test
      •   To Followup
      •  Project A
      •   People
      •   Test
      • Test
    Will the right mailbox please stand up?

    Say you keep track of things to follow-up in multiple mailboxes. When the mailbox hierarchy is expanded, the Move to menu is flattened and it’s very difficult, downright impossible in a timely manner, to determine which Test belongs to which folder and which account.

    You might say, “Okay, I’ll just collapse my mailbox hierarchy before I file any messages.” The problem with this is what happens if you’re looking at a deeply nested mailbox and you want to another mailbox that is hard to disambiguate? If you collapse the mailbox hierarchy, Mail will remove focus from your message and show a blank screen.

    Mailbox hierarchy has been collapsed, but focus on the message has disappeared.

    Enforce Unique Mailbox Names

    One way around this is to enforce unique mailbox names, or at least allow filing when MsgFiler can locate one and only one mailbox. Question for current and past MsgFiler owners is how often do you have mailboxes with the same name across accounts and in different mailboxes? Leave your response in a comment below.

    Question for current and past MsgFiler owners is how often do you have mailboxes with the same name across accounts and in different mailboxes?

    Special Gmail Folders

    The Move to menu method has another weakness. The mailbox path for Gmail’s special mailboxes like Important, Archive, Trash, Junk, etc. are prefixed with the string [Gmail], which is not displayed in the Move to > Message menu. So, there’s no way to target these mailboxes using the Move to AppleScript method.

    App Sandbox and System Events

    There’s an even bigger problem with updating MsgFiler and that is its use of System Events to send commands and key codes to the Mail application. While MsgFiler has a temporary entitlement to control Apple Mail via AppleScript, it does not have an entitlement for sending AppleScript to System Events. Nor is Apple providing such an entitlement, since that can be a vector for sending arbitrary key strokes and commands to any application.

    As a result, any solution using these two methods will likely cause MsgFiler to be rejected by the Mac App Store. I will have to pull MsgFiler from the App Store and find an alternative distribution mechanism with the app (i.e. Gumroad?). This means adding back in license code validation and other things I really don’t want to have to do.

    More Challenges Ahead

    These are some of the challenges that I’m working through to get MsgFiler to work on macOS Sonoma. The degree of difficult is why I continue to recommend the workarounds posted before or just to manually file in the Mail app.

    It’s looking unlikely that I’ll be able to get 100% feature parity with MsgFiler 3 + Engine, but maybe I don’t need to. How many people have mailboxes with the same name? If the number is small, I can accelerate the Move to menu approach. If people don’t mind some slowdown, maybe the pure AppleScript approach will work better.

    Of course, all of this can be solved if Apple just were to implement MsgFiler’s functionality into the native Mail app directly. Sherlock MsgFiler, Apple! Please continue to leave feedback to the Apple Mail team by emailing: mail-app-extensions@apple.com

    Which approach do you like and why? Let me know your thoughts in the comments below.

    37 thoughts on “A Deep Dive Into Filing Mail Messages Using AppleScript”

    1. Thanks for the deep dive Adam. I have many instances where I have the same named mailboxes in different sub-folders. (ie an annual project that has the same set of sub-folders but maybe the second level is the year of that project with the sub-folders having the same name.) It’s less frequent that I have the same named mailboxes across accounts, but I do have some of that. (ie I do similar work for different clients, and in some cases have email accounts I use specific to that client – so one clients “website” folder might also be called “website” for another client and might be in a different account.)

      1. How often are the folder structures completely expanded, meaning you would see two or more “website” folders at the same time?

        Maybe an approach is have both options — filing via AppleScript’s set mailbox or using the faster menu approach — and let users decide which to use?

        Feel free to send me an email with a screenshot of your typical folder structure.

        1. Thanks Adam. I can’t find your email but here’s a screenshot ofmy msgfiler interface after typing the word “entries” (Annual poetry contest…you can see the same mailbox name in multiple years of the project.) https://capture.dropbox.com/tdofn61G3fx8QE2k

          I rarely have the Mailboxes pane expanded, relying on MsgFiler to navigate to mailboxes so I’m not sure whether they’re expanded or not.

          Also, although I do have gmail, IMAP, iCloud and Exchange accounts, 99.99% of the time I am filing to Mailboxes in On My Mac.

    2. You have really been through the mill look at all the scenarios!

      I’m still in Ventura on my MBP M1 2021 mainly because of MsgFiler. Also I’m not really sure what’s compelling about Sonoma – though it’s probably a good idea to stay up-to-date.

      In answer to your requested comment, in my fairly complicated hierarchy of 7 accounts (4 gmail, 1 iCloud, 2 generic IMAP) I would say I just have a few duplicate mailbox names (e.g. in my personal account I have a finance folder and in my work account I have a finance folder, each with their own set of sub-folders).

      I would not have a problem making the names unique if that was helpful.

      As far as which method is the best it’s hard for me to judge. I’ve tried the CMD+Shift-/ method a few times and while clunky it does work. I didn’t notice having to collapse my hierarchy.

      I’m really surprised Apple hasn’t added a simple move feature where you can type a few letters of target mailbox in a search box. They have that in iOS Mail since iOS 17 finally! It’s hard for me to believe it’s not really there. But I don’t want to upgrade just to test that.

      I’ve also looked at other Mac mail apps which have filing features, but they all have drawbacks. For example, the Mac version of Outlook (unlike the Windows version) doesn’t have image annotation (e.g. add text and arrows to images in your email!). Neither does Spark. Some don’t have “send again.” Except for this filing business, Mac Mail is quite nice.

    3. I posted directly on the blog, but I think maybe it got lost somewhere in the login process. Just in case…

      I still haven’t upgraded to Sonoma, mostly because of MsgFiler. Also I don’t know what’s compelling about Sonoma, thought it’s probably a good idea to keep up-to-date.

      I have 7 accounts in Mail: 4 Gmail, 1 iCloud, 2 generic IMAP.

      While I have loads of mailboxes, and a hierarchy of them to keep things sorted, I only have a few truly duplicate names. I would not mind making them unique.

      I’m amazed a simple search field for a mailbox is not part of Sonoma Mail. They even added it to iOS 17 Mail.

      I’ve tried some other mail clients just in case. But they are all missing something. For example, the Mac version of Outlook doesn’t let you annotate embedded images (e.g. add arrows and text), even though the Windows version does. Neither does Spark or Mimestream.

      I’ve experimented with the CMD-Shift-/ keystroke for filing. It seems to work, even without collapsing my mailboxes. It’s sort of clunky though.

      I look forward to hearing what happens, though it sounds difficult from what you wrote. Interesting explanation though!

      >

      1. How often do you file across accounts vs. filing only Gmail to Gmail, iCloud to iCloud, and IMAP to IMAP? How often do you file multiple messages that span different accounts?

        1. Somewhat often. I might have a new root folder for each year (named 2020, 2021, 2022, 2023, 2024, etc.), but under it I could have folders named; sales marketing operations legal, etc.

        2. Understood. Do you often have your mailboxes expanded on the left-hand side of a MessageViewer window? Where you can see 2020 > Sales, 2021 > Sales, 2022 > Sales, etc.? If so, the pure AppleScript method of filing would be better suited for you, although we would still run into the problem of selecting multiple messages — including Gmail — from different accounts and filing them into a folder. AppleScript won’t be able to archive the message before moving it, leaving a copy in your inbox.

        3. Adam, I have some mailboxes expanded but not all. I use apple mail, not gmail. I’m currently using Ike’s Keyboard Maestro’s script/macro and it works very well. I hope this information is helpful. Thanks for all of your time and effort.

        4. It seems my reply didn’t get through the email reply.

          I never file multiple messages that span different accounts. I have it set to only show matches from the current account.

          Very occasionally I will move an email to a different account’s inbox. But I always do that by dragging.

    4. Hi Adam,

      Thank you for the technique descriptions, but I didn’t read them. As I’ve written you before, most of my mail is from the same addresses and the desired mailbox is accordingly suggested automatically. I use the Move with MsgFiler command when it isn’t. When it is, I use the following Keyboard Maestro macro to click on the suggested mailbox:

      So I’m okay.

      Best wishes,

      Roy McCoy Nuevo Arenal, Costa Rica

      >

    5. I have been using message filer without the engine on Sonoma and it is working well – messages filed and are in mailbox folder on my mac. A little slower sometimes but it is working fine. w/r, David

      >

      1. Filing to the On My Mac folder works because there’s no Gmail shenanigans happening behind the scenes with AppleScript. The differences in the kinds of email provider people use and where they file messages to is why MsgFiler works for some people and not for other people.

        1. Curious about this. I have gmail but am almost always filing to On My Mac folders. Can you file from gmail accounts into On My Mac in Sonoma. Is the issue here (with the current MsgFiler) just that it won’t reliably file to folders outside of OnMyMac?

        2. The question is what happens when you move the message from the Gmail account to On My Mac. I’ve seen the message get moved but stay in the inbox because Gmail hasn’t updated itself (it still thinks it’s in the Inbox). Again, this is when using the AppleScript method to “set mailbox” of the message. It behaves differently if you drag and drop the email in Mail.

    6. For what it’s worth, while I have a bunch of folders with nested sub-folders, some with several layers of nesting, as far as I can tell, I have no duplicate folder names.

      Also, I have no gmail accounts, so there’s that.

      As a result, MsgFiler has continued to work, as best I can tell, flawlessly for me under Sonoma.

    7. Hi Adam,

      FIrst, thanks SO MUCH for all the work you’re putting into this. I also appreciate the very detailed description of why this has become such a complex programming problem.

      First, I almost never move messages from one account to another. That is, from Gmail to iCloud or vice versa.

      Second, I do have some same filenames in both accounts. I have about 50 “labels” in Gmail, and about 10 in iCloud. I could easly rename the iCloud folders from, for example, “Taxes” to “Taxes.i” etc. That actually makes sense because when I’m in a hurry, I sometimes mistake the two.

      Third, I have multiple Gmail accounts, but there’s no big issue with the same labels among the Gmail accounts, because I use each one differently.

      Fourth, I’m considering subscribing to Proton Mail. Hope that wouldn’t throw a monkey wrench in the works.

      Thanks you again.

      Bruce

    8. l am a happy user of MsgFiles in Sonoma (with no engine). I don’t have a Gmail account. I never had a problem. I use MsgFiler quite frequently, and, even with a mailbox 30GB big, I don’t see any slow down – maybe because I have a M2 MacBook Pro.

    9. I’m in the group that doesn’t use gmail and has no problems with MsgFiler 3.1.4 in Sonoma.

      I can understand and appreciate your efforts to come up with a solution that works for everyone but I sincerely hope this doesn’t come at the expense of reduced functionality.

      If this is impossible, may I suggest you continue to support the current version for those of us who would like to keep using it. Unless Apple decides to include equivalent functionality directly in Mail, I would gladly pay to support your efforts to maintain what I view as an indispensable tool.

    10. Hi Adam, thanks for all of your work to try to make a new version of MsgFiler. I rely on it it daily and I’m keeping my Mac on macOS 13 Ventura so I can continue to use MsgFiler.

      Here are my answers to your questions.
      1. All of my mailboxes have unique names.

      2. I rarely, if ever, need to file messages into a folder belonging to another email account. I do select a handful or more messages and file them into a folder but those folders belong to the same account.

      For what it’s worth, I have 8 email accounts setup in Mail and they are a mix of iCloud, Gmail, Yahoo, Microsoft 365 and Outlook.com accounts. I do most of my filing in the iCloud, Microsoft 365 and Yahoo accounts.

      3. The biggest feature I use in MsgFiler is the Move command. I also use the Show command very often, since it’ll auto-expand my large mailbox hierarchy. Once my hierarchy is expanded, I often like to collapse it. I typically do this by pressing Command-Option and click on a parent folder which these collapses the hierarchy.

      4. I never use the Label, Excluded Mailboxes or Favorite features.

      Thanks for posting Apple’s email address so we can send them feedback. I’ll do that. I hope you’re able to build a product for us. I’m fine if Apple builds these capabilities into the Mail application. In fact I think they are long overdue. So many people are overwhelmed by their Inboxes. If Mail offered a way to quickly and easily file messages, that could help many folks. I’m so pleased that Apple added Tabs and Send Later to Mail. Even if Apple does add a filing feature into Mail, I don’t think it’ll show up soon so please build a new MsgFiler to fill the gap.

      1. Thanks. I’m working hard on getting a beta that people can test. When it’s available, I recommend using it one non-essential email like spam, newsletters, etc. Since you have a variety of accounts, I’m curious to see how it behaves for you (esp. those 365 and Outlook accounts).

    11. Hi Adam,
      I’m so happy to read the word “beta” from you, I could nearly cry. I’ve been on Sonoma for some time without MsgFilter and it seriously inhibits my productivity. As a person with disabilities, having MsgFilter allowed me to keep pace with everyone else. I’m so disappointed with Apple for leaving us behind.

      Here are my answers to your questions.
      1. All of my mailboxes have unique names, other than “Inbox”

      2. All my messages are filed locally. I will select multiple messages and move them into a single folder, with the source messages always coming from the same account.

      I have nine accounts. One is iCloud. One is Gmail. Five are Google Workspace. Two are O365.

      3. I use the search and move command constantly. I also use the show command frequently. I never use the copy command.

      4. I never use the Label or Excluded Mailboxes. I do use the Favorite features.

      I’m a software developer (CSE), so I hope to be valuable to your beta.

      1. Hoping to have a beta soon via TestFlight. Don’t have the favorites feature implemented yet, and not sure if it’s going to come for the initial beta (or final release). That said, I think you’ll find the app very familiar. Stay tuned!

    12. Thanks Adam. I’m still using MsgFiler with Sonoma and with Gmail, without problems, probably because all my folders have different names. Mike

    13. Hi Adam, still using MsgFiler with Ventura thanks to its great functionality. Not technical at all but happy to wait. I would willingly rename my many folders to ensure they are different, but have a University Gmail IMAP account and personal Gmail account so would have to work on the latter. But it shouldn’t take too long. Much better than spending hours filing the over 100 emails I receive every day! Simon

    Leave a comment

    This site uses Akismet to reduce spam. Learn how your comment data is processed.