AutoSwitch Mu4e context depending on mailbox

The reason

There are a few things that depend on the context in Mu4e, some of which are mentioned in the documentation…

It can be useful to switch between different sets of settings in Mu4e; a typical example is the case where you have different e-mail accounts for private and work email, each with their own values for folders, e-mail addresses, mailservers and so on.

Personally I need to be in the right context since I use multiple accounts in my setup. For instance:

  • The right sender needs to be selected when composing an email
  • The right variables mu4e-refile-folder need to be correct when refiling/archiving emails
  • And more…

As it turns out, the right context is not always selected when switching mailboxes in the way my contexts are configured. Meaning I need a more robust solution.

When switching to a mailbox using timu-mu4e-jump-to-maildir – especially into a mailbox of a different account – Mu4e does not switch the context correctly. At least that has been my experience.

The solution

The code I use has a prerequisite however. The email directories (maildir) for each account need to have the exact same name as the account in the Mu4e inside Emacs.

The function uses mu4e~headers-mode-line-label to get the current maildir string and uses REGEXP to obtain the name of the account this then used as the current context using mu4e-context-switch.

(defun timu-mu4e-switch-context ()
  "Switch context of the current maildir.
Uses `mu4e~headers-mode-line-label' and regex to get the context."
  (let* ((new-context
          (let ((input mu4e~headers-mode-line-label))
            (string-match "maildir:\"/\\(.+\\)/.*\"" input)
            (match-string 1 input))))
    (if new-context
        (mu4e-context-switch t new-context)
      (mu4e-context-switch t "icloud"))))

This function is then used as a mu4e-headers-found-hook which is of course applied whenever I switch to a mailbox, meaning to a headers view.

(add-hook 'mu4e-headers-found-hook #'timu-mu4e-switch-context)

The conclusion

I am certain that there exists a better solution out there. I could probably rewrite the setup of the Mu4e context in my configuration to make it more robust.

But since the current solution works wonders for me – I know this is hyperbolic – I cannot be bothered to look more into it.