Closing all Mail document windows ? (Leaving Inbox open)

I may be missing something about OS X Mail, but I often find that I have a largish number of email windows open, and want to close them all without closing the Inbox window.

Would not be surprised to learn that there is already a keystroke, but in the meanwhile, here is a 土办法 (inelegant hack : - ) for 10.10 or 10.11 (uses a JS for Automation action)

Close all Mail windows except Inbox.kmmacros (18.6 KB)

(function () {

  var lngClosed = [].concat.apply(
    [],
    Application("Mail").windows().map(
      function (x) {
        return x.name().substr(0, 5) === 'Inbox' ? [] : [x.close()];
      }
    )
  ).length;

  return "MAIL: " + (lngClosed ? (
    lngClosed + " Mail window" +
    (lngClosed > 1 ? 's' : '') + ' closed'
  ) : '( No windows to close )');

})();

The cheat method for this is generally: Close All Windows, Open Message Viewer. Command-Shift-W, Command-0.

@ComplexPoint’s method is more elegant of course, but for those folks lacking the scripting skills, the cheat method is pretty effective (or they can of course ask here and some kind fellow like @ComplexPoint would no doubt help them out!)

1 Like

Would this work? It was simple to cobble together — so I assume I'm missing something even worse than 土办法 .

_Attempt to close all Mail windows but the Inbox.kmmacros (4.6 KB)

I suppose the first thing to amend would be to set it to work when the user does not have the Message Viewer open to the Inbox.

Two things:

  1. Since Yosemite scripting in Mail has become quite flakey. A number of things which used to work are now broken. My particular issue is closing the preview window, but that’s another story.

  2. You might want to rethink your email habits.

A couple of tidbits.

tell application "Mail"
  close (windows whose name does not start with "Inbox")
end tell

Leave any and all message-viewers open:

tell application "Mail"
  set msgViewerList to name of message viewers
  repeat with theWindow in (get windows)
    if name of theWindow is not in msgViewerList then close theWindow
  end repeat
end tell

-Chris

1 Like

Those are way more than "tidbits", my friend. They are huge chunks meat. :+1:
Added to my code snippets.
Many thanks!

1 Like

Good idea.

In JS, you might write something like:

(function () {

    var m = Application("Mail"),
        lstNames = m.messageViewers().map(function (v) {
            return v.name();
        }),
        lngClosed = 0;

    m.windows().forEach(function (w) {
        if (lstNames.indexOf(w.name()) === -1) {
            w.close();
            lngClosed += 1;
        };
    });
    
    return lngClosed;
   
})();

or perhaps:

(function () {

	var m = Application("Mail"),
		lstNames = m.messageViewers().map(function (v) {
			return v.name();
		});

	return m.windows().reduce(function (a, w) {
		return -1 === lstNames.indexOf(w.name()) ?
			w.close() || a + 1 : a;
	}, 0);

})();