     [file version.texi not included]

Copyright © 2012-2023 Dirk-Jan C. Binnema

     Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.  A copy of the license is included in the section entitled ``GNU Free Documentation License.''

mu4e manual
***********

Welcome to mu4e!

mu4e (mu-for-emacs) is an e-mail client for GNU Emacs version 26.3 or newer, built on top of the mu (https://www.djcbsoftware.nl/code/mu) e-mail search engine. mu4e is optimized for quickly processing large amounts of e-mail.

Some of its highlights:

  * Fully search-based: there are no folders (that is, instead of folders, you use queries that match messages in a particular folder), only queries.

  * Fully documented, with example configurations

  * User-interface optimized for speed, with quick key strokes for common actions

  * Support for non-English languages (so ``angstrom''  matches ``Ångström'')

  * Asynchronous: heavy actions don't block emacs (currently, the only exception to this is sending mail; there are solutions for that though --- see the FAQ)

  * Support for cryptography --- signing, encrypting and decrypting

  * Address auto-completion based on the contacts in your messages

  * Extendable with your own snippets of elisp

In this manual, we go through the installation of mu4e, do some basic configuration and explain its daily use. We also show you how you can customize mu4e for your special needs.

At the end of the manual, there are some example configurations, to get you up to speed quickly: Example configurations. There's also a section with answers to frequently asked questions, FAQ.

Introduction
************

Let's get started!q

Why another e-mail client?
==========================

I (mu4e's author) spend a lot of time dealing with e-mail, both professionally and privately. Having an efficient e-mail client is essential. Since none of the existing ones worked the way I wanted, I thought about creating my own.

Emacs is an integral part of my workflow, so it made a lot of sense to use it for e-mail as well. And as I had already written an e-mail search engine (mu), it seemed only logical to use that as a basis.

Other mail clients
==================

Under the hood, mu4e is fully search-based, similar to programs like notmuch (https://notmuchmail.org/) and sup (https://sup-heliotrope.github.io/).

However, mu4e's user-interface is quite different. mu4e's mail handling (deleting, moving, etc.) is inspired by Wanderlust (http://www.gohome.org/wl/) (another Emacs-based e-mail client), mutt (http://www.mutt.org/) and the dired file-manager for emacs.

mu4e keeps all the `state' in your maildirs, so you can easily switch between clients, synchronize over IMAP, backup with rsync and so on. The Xapian-database that mu maintains is merely a cache; if you delete it, you won't lose any information.

What mu4e does not do
=====================

There are a number of things that mu4e does not do, by design:

  * mu/mu4e do not get your e-mail messages from a mail server. Nor does it sync-back any changes. Those tasks are delegated to other tools, such as offlineimap (https://www.offlineimap.org/), isync/mbsync (http://isync.sourceforge.net/) or fetchmail (http://www.fetchmail.info/); As long as the messages end up in a maildir, mu4e and mu are happy to deal with them.

  * mu4e also does not implement sending of messages; instead, it depends on smtpmail (smtpmail), which is part of Emacs. In addition, mu4e piggybacks on Gnus' message editor.

Thus, many of the things an e-mail client traditionally needs to do, are delegated to other tools. This leaves mu4e to concentrate on what it does best: quickly finding the mails you are looking for, and handle them as efficiently as possible.

Becoming a mu4e user
====================

If mu4e sounds like something for you, give it a shot! We're trying hard to make it as easy as possible to set up and use; and while you can use elisp in various places to augment mu4e, a lot of knowledge about programming or elisp shouldn't be required. The idea is to provide sensible defaults, and allow for customization.

When you take mu4e into use, it's a good idea to subscribe to the mu/mu4e-mailing list (https://groups.google.com/group/mu-discuss).

Sometimes, you might encounter some unexpected behavior while using mu4e. It could be a bug in mu4e, it could be an issue in other software. Or it could just be a misunderstanding. In any case, if you want to report this (either to the mailing list or to https://github.com/djcb/mu/issues, the latter is preferred), please always include the following information:

  * what did you expect that should happen? what actually happened?

  * can you provide some exact steps to reproduce?

  * what version of mu4e and emacs were you using? What operating system?

  * can you reproduce it with emacs -q and only loading mu4e?

  * if the problem is related to some specific message, please include the raw message file (appropriately anonymized, of course)

Getting started
***************

In this chapter, we go through the installation of mu4e and its basic setup. After we have succeeded in Getting mail, and see Indexing your messages, we discuss the Basic configuration.

After these steps, mu4e should be ready to go!

Requirements
============

mu/mu4e are known to work on a wide variety of Unix- and Unix-like systems, including many Linux distributions, OS X and FreeBSD, and even on MS-Windows (with Cygwin). Emacs 26.3 or higher is required, as well as Xapian (https://xapian.org/) and GMime (http://spruce.sourceforge.net/gmime/).

mu has optional support for the Guile (Scheme) programming language (version 3.0 or higher). There are also some GUI-toys, which require GTK+ 3.x and Webkit.

If you intend to compile mu yourself, you need to have the typical development tools, such as C and C++17 compilers (both gcc and clang should work), meson and make, and the development packages for GMime 3.x, GLib and Xapian. Optionally, you also need the development packages for GTK+, Webkit and Guile.

Versions
========

The stable (release) versions have even minor version numbers, while the development versions have odd ones. So, for example, 1.8.13 is a stable version, while the 1.9.9 is the development version.

The stable versions only receive bug fixes after being released, while the development versions get new features, fixes, and, perhaps, bugs, and are meant for people with a tolerance for that.

There is support for one release branch; so, when the 1.10 release is available (and a new 1.11 development series start), no more changes are expected for the 1.8 releases.

Installation
============

mu4e is part of mu --- by installing the latter, the former is installed as well. Some Linux distributions provide packaged versions of mu/mu4e; if you can use those, there is no need to compile anything yourself. However, if there are no packages for your distribution, if they are outdated, or if you want to use the latest development versions, you can follow the steps below.

Dependencies
------------

The first step is to get some build dependencies. The details depend a bit on your system's setup / distribution.

  * On Debian/Ubuntu and derivatives:

          $ sudo apt-get install git meson libgmime-3.0-dev libxapian-dev emacs

  * On Fedora and related:

          $ sudo dnf install git meson gmime30-devel xapian-core-devel emacs

  * Otherwise, install the equivalent of the above on your system

Getting mu
----------

The next step is to get the mu sources. There are two alternatives:

  * Use a stable release -- download a release from https://github.com/djcb/mu/releases

  * Use an experimental development version -- get it from the repository, and git clone https://github.com/djcb/mu.git

Building mu
-----------

What all that in place, let's build and install mu and mu4e. Enter the directory where you unpacked or cloned mu. Then:

     $ ./configure && make
     $ sudo make install

Note: if you are familiar with meson, you can of course use its commands directly; the make commands are just a thin wrapper around that.

Installation
------------

After this, mu and mu4e should be installed  (there's a hard dependency between versions of mu4e and mu --- you cannot combine different versions) on your system, and be available from the command line and in Emacs.

You may need to restart Emacs, so it can find mu4e in its load-path. If, even after restarting, Emacs cannot find mu4e, you may need to add it to your load-path explicitly; check where mu4e is installed, and add something like the following to your configuration before trying again:

     ;; the exact path may differ --- check it
     (add-to-list 'load-path "/usr/local/share/emacs/site-lisp/mu4e")

mu4e and emacs customization
----------------------------

There is some support for using the Emacs customization system in mu4e, but for now, we recommend setting the values manually. Please refer to Example configurations for a couple of examples of this; here we go through things step-by-step.

Getting mail
============

In order for mu (and, by extension, mu4e) to work, you need to have your e-mail messages stored in a maildir (https://en.wikipedia.org/wiki/Maildir; in this manual we use the term `maildir' for both the standard and the hierarchy of maildirs that store your messages) --- a specific directory structure with one-file-per-message.

If you are already using a maildir, you are lucky. If not, some setup is required:

  * Using an external IMAP or POP server --- if you are using an IMAP or POP server, you can use tools like getmail, fetchmail, offlineimap or isync to download your messages into a maildir (~/Maildir, often). Because it is such a common case, there is a full example of setting mu4e up with offlineimap and Gmail; see Gmail configuration.

  * Using a local mail server --- if you are using a local mail- server (such as postfix or qmail), you can teach them to deliver into a maildir as well, maybe in combination with procmail. A bit of googling should be able to provide you with the details.

While a mu only supports a single Maildir, it can be spread across different file-systems; and symbolic links are supported.

Initializing the message store
==============================

The first time you run mu, you need to initialize its store (database). The default location for that is ~/.cache/mu/xapian, but you can change this using the --muhome option, and remember to pass that to the other commands as well. Alternatively, you can use an environment variable MUHOME.

Assuming that your maildir is at ~/Maildir, we issue the following command:

       $ mu init --maildir=~/Maildir

You can add some e-mail addresses, so mu recognizes them as yours:

       $ mu init --maildir=~/Maildir --my-address=jim@example.com \
         --my-address=bob@example.com

mu remembers the maildir and your addresses and uses them when indexing messages. If you want to change them, you need to init once again.

The addresses may also be basic PCRE regular expressions, wrapped in slashes, for example:

       $ mu init --maildir=~/Maildir '--my-address=/foo-.*@example\.com/'

If you want to see the values for your message-store, you can use mu info.

Indexing your messages
======================

After you have succeeded in Getting mail and initialized the message database, we need to index the messages. That is --- we need to scan the messages in the maildir and store the information about them in a special database.

We can do that from mu4e --- Main view, but the first time, it is a good idea to run it from the command line, which makes it easier to verify that everything works correctly.

Assuming that your maildir is at ~/Maildir, we issue the following command:

       $ mu index

This should scan your messages and fill the database, and give progress information while doing so.

The indexing process may take a few minutes the first time you do it (for thousands of e-mails); afterwards it is much faster, since mu only scans messages that are new or have changed. Indexing is discussed in full detail in the mu-index man-page.

After the indexing process has finished, you can quickly test if everything worked, by trying some command-line searches, for example

       $ mu find hello

which lists all messages that match hello. For more examples of searches, see Queries, or check the mu-find and mu-easy man pages. If all of this worked well, we are well on our way setting things up; the next step is to do some basic configuration for mu4e.

Basic configuration
===================

Before we can start using mu4e, we need to tell Emacs to load it. So, add to your ~/.emacs (or its moral equivalent, such as ~/.emacs.d/init.el) something like:

     (require 'mu4e)

If Emacs complains that it cannot find mu4e, check your load-path and make sure that mu4e's installation directory is part of it. If not, you can add it:

     (add-to-list 'load-path MU4E-PATH)

with MU4E-PATH replaced with the actual path.

Folders
=======

The next step is to tell mu4e where it can find your Maildir, and some special folders.

So, for example (Note that the folders (mu4e-sent-folder, mu4e-drafts-folder, mu4e-trash-folder and mu4e-refile-folder) can also be functions that are evaluated at runtime. This allows for dynamically changing them depending on the situation. See Dynamic folders for details.):

     ;; these are actually the defaults
     (setq
       mu4e-sent-folder   "/sent"       ;; folder for sent messages
       mu4e-drafts-folder "/drafts"     ;; unfinished messages
       mu4e-trash-folder  "/trash"      ;; trashed messages
       mu4e-refile-folder "/archive")   ;; saved messages

The folder (maildir) names are all relative to the root-maildir (see the output of mu info). If you use mu4e-context, see Contexts and special folders for what that means for these special folders.

Retrieval and indexing with mu4e
================================

As we have seen, we can do all of the mail retrieval outside of Emacs/mu4e. However, you can also do it from within mu4e.

Basics
------

To set up mail-retrieval from within mu4e, set the variable mu4e-get-mail-command to the program or shell command you want to use for retrieving mail. You can then get your e-mail using M-x mu4e-update-mail-and-index, or C-S-u in all mu4e-views; alternatively, you can use C-c C-u, which may be more convenient if you use emacs in a terminal.

You can kill the (foreground) update process with q.

It is possible to update your mail and index periodically in the background or foreground, by setting the variable mu4e-update-interval to the number of seconds between these updates. If set to nil, it won't update at all. After you make changes to mu4e-update-interval, mu4e must be restarted before the changes take effect. By default, this will run in background and to change it to run in foreground, set mu4e-index-update-in-background to nil.

Handling errors during mail retrieval
-------------------------------------

If the mail-retrieval process returns with a non-zero exit code, mu4e shows a warning (unless mu4e-index-update-error-warning is set to nil), but then try to index your maildirs anyway (unless mu4e-index-update-error-continue is set to nil).

Reason for these defaults is that some of the mail-retrieval programs may return non-zero, even when the updating process succeeded; however, it is hard to tell such pseudo-errors from real ones like `login failed'.

If you need more refinement, it may be useful to wrap the mail-retrieval program in a shell-script, for example fetchmail returns 1 to indicate `no mail'; we can handle that with:

     (setq mu4e-get-mail-command "fetchmail -v || [ $? -eq 1 ]")

A similar approach can be used with other mail retrieval programs, although not all of them have their exit codes documented.

Implicit mail retrieval
-----------------------

If you don't have a specific command for getting mail, for example because you are running your own mail-server, you can leave mu4e-get-mail-command at "true" (the default), in which case mu4e won't try to get new mail, but still re-index your messages.

Speeding up indexing
--------------------

If you have a large number of e-mail messages in your store, (re)indexing might take a while. The defaults for indexing are to ensure that we always have correct, up-to-date information about your messages, even if other programs have modified the Maildir.

The downside of this thoroughness (which is the default) is that it is relatively slow, something that can be noticeable with large e-mail corpa on slow file-systems. For a faster approach, you can use the following:

     (setq
       mu4e-index-cleanup nil      ;; don't do a full cleanup check
       mu4e-index-lazy-check t)    ;; don't consider up-to-date dirs

In many cases, the mentioned thoroughness might not be needed, and these settings give a very significant speed-up. If it does not work for you (e.g., mu4e fails to find some new messages), simply leave at the default.

Note that you can occasionally run a thorough indexing round using mu4e-update-index-nonlazy.

For further details, please refer to the mu-index manpage; in particular, see .noindex and .noupdate which can help reducing the indexing time.

Example setup
-------------

A simple setup could look something like:

     (setq
       mu4e-get-mail-command "offlineimap"   ;; or fetchmail, or ...
       mu4e-update-interval 300)             ;; update every 5 minutes

A hook mu4e-update-pre-hook is available which is run right before starting the process. That can be useful, for example, to influence, mu4e-get-mail-command based on the the current situation (location, time of day, ...).

It is possible to get notifications when the indexing process does any updates --- for example when receiving new mail. See mu4e-index-updated-hook and some tips on its usage in the FAQ.

Sending mail
============

mu4e re-uses Gnus' message-mode (message) for writing mail and inherits the setup for sending mail as well.

For sending mail using SMTP, mu4e uses smtpmail (smtpmail). This package supports many different ways to send mail; please refer to its documentation for the details.

Here, we only provide some simple examples --- for more, see Example configurations.

A very minimal setup:

     ;; tell message-mode how to send mail
     (setq message-send-mail-function 'smtpmail-send-it)
     ;; if our mail server lives at smtp.example.org; if you have a local
     ;; mail-server, simply use 'localhost' here.
     (setq smtpmail-smtp-server "smtp.example.org")

Since mu4e (re)uses the same message mode and smtpmail that Gnus uses, many settings for those also apply to mu4e.

Dealing with sent messages
--------------------------

By default, mu4e puts a copy of messages you sent in the folder determined by mu4e-sent-folder. In some cases, this may not be what you want - for example, when using Gmail-over-IMAP, this interferes with Gmail's handling of the sent messages folder, and you may end up with duplicate messages.

You can use the variable mu4e-sent-messages-behavior to customize what happens with sent messages. The default is the symbol sent which, as mentioned, causes the message to be copied to your sent-messages folder. Other possible values are the symbols trash (the sent message is moved to the trash-folder (mu4e-trash-folder), and delete to simply discard the sent message altogether (so Gmail can deal with it).

For Gmail-over-IMAP, you could add the following to your settings:
;; don't save messages to Sent Messages, Gmail/IMAP takes care of this
(setq mu4e-sent-messages-behavior 'delete)
And that's it! We should now be ready to go.

For more complex needs, mu4e-sent-messages-behavior can also be a parameter-less function that returns one of the mentioned symbols; see the built-in documentation for the variable.

Running mu4e
============

After following the steps in this chapter, we now (hopefully!) have a working mu4e setup. Great! In the next chapters, we walk you through the various views in mu4e.

For your orientation, the diagram below shows how the views relate to each other, and the default key-bindings to navigate between them.

   [C]       +--------+   [RFCE]
   --------> | editor | <--------
  /          +--------+          \
 /         [RFCE]^                \
/                |                 \
+-------+ [sjbB]+---------+  [RET]  +---------+
| main  | <---> | headers | <---->  | message |
+-------+  [q]  +---------+ [qbBjs] +---------+
                   [sjbB]                ^
[.] | [q]
    V
  +-----+
  | raw |
  +-----+

Default bindings
----------------
R: Reply      s: search            .: raw view (toggle)
F: Forward    j: jump-to-maildir   q: quit
C: Compose    b: bookmark-search
E: Edit       B: edit bookmark-search

The main view
*************

After you have installed mu4e (see Getting started), you can start it with M-x mu4e. mu4e does some checks to ensure everything is set up correctly, and then shows you the mu4e main view. Its major mode is mu4e-main-mode.

Overview
========

The main view looks something like the following:

* mu4e - mu for emacs version x.y.z

  Basics

        * [j]ump to some maildir
        * enter a [s]earch query
        * [C]ompose a new message

  Bookmarks

        * [bu] Unread messages      13085(+3)/13085
        * [bt] Today's messages
        * [bw] Last 7 days          53(+3)/128
        * [bp] Messages with images 75/2441

  Maildirs

        * [ja] /archive             2101/18837
        * [ji] /inbox               8(+2)/10
        * [jb] /bulk                33/35
        * [jB] /bulkarchive         179/2090
        * [jm] /mu                  694(+1)/17687
        * [jn] /sauron
        * [js] /sent

  Misc

        * [;]Switch context
        * [U]pdate email & database
        * toggle [m]ail sending mode (currently direct)
        * [f]lush 1 queued mail

        * [N]ews
        * [A]bout mu4e
        * [H]elp
        * [q]uit

  Info

        * last-updated        : Sat Dec 31 16:43:56 2022
        * database-path       : /home/pam/.cache/mu/xapian
        * maildir             : /home/pam/Maildir
        * in store            : 86179 messages
        * personal addresses  : /.*example.com/, pam@@example.com

Let's walk through the menu.

Basic actions
=============

First, the Basics:

  * [j]ump to some maildir: after pressing j (``jump''), mu4e asks you for a maildir to visit. These are the maildirs you set in Basic configuration and any of your own. If you choose o (``other'') or /, you can choose from all maildirs under the root-maildir. After choosing a maildir, the messages in that maildir are listed, in the Headers view.

  * enter a [s]earch query: after pressing s, mu4e asks you for a search query, and after entering one, shows the results in the Headers view.

  * [C]ompose a new message: after pressing C, you are dropped in the Editor view to write a new message.

Bookmarks and Maildirs
======================

The next two items in the Main view are Bookmarks and Maildirs.

Bookmarks are predefined queries with a descriptive name and a shortcut --- in the example above, we see the default bookmarks. You can view the list of messages matching a certain bookmark by pressing b followed by the bookmark's shortcut. If you want to edit the bookmarked query before invoking it, use B.

Next to each bookmark are some numbers that indicate the unread(delta)/all matching messages for the given query, with the delta being the difference in unread count since some ``baseline'', and only shown when this delta > 0.

Note that the ``delta'' has its limitations: if you, for instance, deleted 5 messages and received 5 new one, the ``delta'' would be 0, although there were changes indeed. So it is mostly useful for tracking changes while you are not using mu4e.

Using a baseline is useful to quickly see that there are new messages since the last time you looked. Imagine switching to another buffer to work on something or even (!) stepping away from your computer to return later: the baseline allows you to quickly see what changed.

The baseline is reset automatically when switching to the main view, or when querying the ``favorite'' query (explained below). You can see the current value using the mu4e-baseline-time command.

Bookmarks are stored in the variable mu4e-bookmarks; you can add your own and/or replace the default ones; see Bookmarks. For instance:

     (add-to-list 'mu4e-bookmarks
       ;; add bookmark for recent messages on the Mu mailing list.
       '( :name "Mu7Days"
          :key  ?m
          :query "list:mu-discuss.googlegroups.com AND date:7d..now"))

There are optional keys :hide to hide the bookmark from the main menu, but still have it available (using b)) and :hide-unread to avoid generating the unread-number; that can be useful if you have bookmarks for slow queries. Note that :hide-unread is implied when the query is not a string; this for the common case where the query function involves some user input, which would be disruptive in this case.

There is also the optional :favorite property, which at most one bookmark should have; this bookmark is highlighted in the main view, and its unread-status is shown in the modeline; see Modeline.

The Maildirs item is very similar to Bookmarks, when you consider maildirs here as being special kind of bookmark that matches some Maildir.

Miscellaneous
=============

Finally, there are some Misc (miscellaneous) actions:

  * [U]pdate email & database executes the shell-command in the variable mu4e-get-mail-command, and afterwards updates the mu database; see Indexing your messages and Getting mail for details.

  * [R]eset query-results baseline this reset the current 'baseline' for query and updates the screen; see Bookmarks and Maildirs.

  * toggle [m]ail sending mode (direct) toggles between sending mail directly, and queuing it first (for example, when you are offline), and [f]lush queued mail flushes any queued mail. This item is visible only if you have actually set up mail-queuing. Queuing mail

  * [A]bout mu4e provides general information about the program

  * [H]elp shows help information for this view

  * Finally, [q]uit mu4e quits your mu4e-session

The headers view
****************

The headers view shows the results of a query. The header-line shows the names of the fields. Below that, there is a line with those fields, for each matching message, followed by a footer line. The major-mode for the headers view is mu4e-headers-mode.

Overview
========

An example headers view:

Date V       Flgs  From/To             List       Subject
06:32        Nu    To Edmund Dantès    GstDev     Gstreamer-V4L2SINK ...
15:08        Nu    Abbé Busoni         GstDev     ├>                 ...
18:20        Nu    Pierre Morrel       GstDev     │└>                ...
07:48        Nu    To Edmund Dantès    GstDev     └>                 ...
2013-03-18   S     Jacopo              EmacsUsr   emacs server on win...
2013-03-18   S     Mercédès            EmacsUsr   └>                 ...
2013-03-18   S     Beachamp            EmacsUsr   Re: Copying a whole...
22:07        Nu    Albert de Moncerf   EmacsUsr   └>                 ...
2013-03-18   S     Gaspard Caderousse  GstDev     Issue with GESSimpl...
2013-03-18   Ss    Baron Danglars      GuileUsr   Guile-SDL 0.4.2 ava...
End of search results

Some notes to explain what you see in the example:

  * The fields shown in the headers view can be influenced by customizing the variable mu4e-headers-fields; see mu4e-header-info for the list of built-in fields. Apart from the built-in fields, you can also create custom fields using mu4e-header-info-custom; see HV Custom headers for details.

  * By default, the date is shown with the :human-date field, which shows the time for today's messages, and the date for older messages. If you do not want to distinguish between `today' and `older', you can use the :date field instead.

  * You can customize the date and time formats with the variable mu4e-headers-date-format and mu4e-headers-time-format, respectively. In the example, we use :human-date, which shows the time when the message was sent today, and the date otherwise.

  * By default, the subject is shown using the :subject field; however, it is also possible to use :thread-subject, which shows the subject of a thread only once, similar to the display of the mutt e-mail client.

  * The header field used for sorting is indicated by ``V'' or ``^'' (or you can use little graphical triangles; see variable mu4e-use-fancy-chars), corresponding to the sort order (descending or ascending, respectively). You can influence this by a mouse click, or O. Not all fields allow sorting.

  * Instead of showing the From: and To: fields separately, you can use From/To (:from-or-to in mu4e-headers-fields as a more compact way to convey the most important information: it shows From: except when the e-mail was sent by the user (i.e., you) --- in that case it shows To: (prefixed by To (You can customize this by changing the variable mu4e-headers-from-or-to-prefix (a cons cell)), as in the example above).

  * The `List' field shows the mailing-list a message is sent to; mu4e tries to create a convenient shortcut for the mailing-list name; the variable mu4e-user-mailing-lists can be used to add your own shortcuts. You can use mu4e-mailing-list-patterns to specify generic shortcuts. For instance, to shorten list names to the part before -list, you could use:

          (setq mu4e-mailing-list-patterns '("\\`\\([-_a-z0-9.]+\\)-list"))

  * The letters in the `Flags' field correspond to the following: D=draft, F=flagged (i.e., `starred'), N=new, P=passed (i.e., forwarded), R=replied, S=seen, T=trashed, a=has-attachment, x=encrypted, s=signed, u=unread. The tooltip for this field also contains this information.

  * The subject field also indicates the discussion threads  (using Jamie Zawinski's mail threading algorithm, https://www.jwz.org/doc/threading.html).

  * The headers view is automatically updated if any changes are found during the indexing process, and if there is no current user-interaction. If you do not want such automatic updates, set mu4e-headers-auto-update to nil.

  * Just before executing a search, a hook-function mu4e-search-hook is invoked, which receives the search expression as its parameter.

  * Also, there is a hook-function mu4e-headers-found-hook available which is invoked just after mu4e has completed showing the messages in the headers-view.

Keybindings
===========

Using the below key bindings, you can do various things with these messages; these actions are also listed in the Headers menu in the Emacs menu bar.

key          description
===========================================================
n,p          view the next, previous message
],[          move to the next, previous unread message
y            select the message view (if it's visible)
RET          open the message at point in the message view

searching
---------
s            search
S            edit last query
/            narrow the search
b            search bookmark
B            edit bookmark before search
j            jump to maildir
M-left,\     previous query
M-right      next query

O            change sort order
P            toggle search property

marking
-------
d            mark for moving to the trash folder
=            mark for removing trash flag ('untrash')
DEL,D        mark for complete deletion
m            mark for moving to another maildir folder
r            mark for refiling
+,-          mark for flagging/unflagging
?,!          mark message as unread, read

u            unmark message at point
U            unmark *all* messages

%            mark based on a regular expression
T,t          mark whole thread, subthread

<insert>,*   mark for 'something' (decide later)
#            resolve deferred 'something' marks

x            execute actions for the marked messages

composition
-----------
R,F,C        reply/forward/compose
E            edit (only allowed for draft messages)

misc
----
a            execute some custom action on a header
|            pipe message through shell command
C-+,C--      increase / decrease the number of headers shown
H            get help
C-S-u        update mail & reindex
C-c C-u      update mail & reindex
q            leave the headers buffer

Furthermore, a number of keybindings are available through minor modes:

  * Context; see Contexts.

Marking
=======

You can mark messages for a certain action, such as deletion or move. After one or more messages are marked, you can then execute (mu4e-mark-execute-all, x) these actions. This two-step mark-execute sequence is similar to what e.g. dired does. It is how mu4e tries to be as quick as possible, while avoiding accidents.

The mark/unmark commands support the region (i.e., ``selection'') --- so, for example, if you select some messages and press DEL, all messages in the region are marked for deletion.

You can mark all messages that match a certain pattern with %. In addition, you can mark all messages in the current thread (T) or sub-thread (t).

When you do a new search or refresh the headers buffer while you still have marked messages, you are asked what to do with those marks --- whether to apply them before leaving, or ignore them. This behavior can be influenced with the variable mu4e-headers-leave-behavior.

For more information about marking, see Marking.

Sorting and threading
=====================

By default, mu4e sorts messages by date, in descending order: the most recent messages are shown at the top. In addition, be default mu4e shows the message threads, i.e., the tree structure representing a discussion thread; this also affects the sort order: the top-level messages are sorted by the date of the newest message in the thread.

The header field used for sorting is indicated by ``V'' or ``^'' (or you can use little graphical triangles; see variable mu4e-use-fancy-chars), indicating the sort order (descending or ascending, respectively).

You can change the sort order by clicking the corresponding column with the mouse, or with M-x mu4e-headers-change-sorting (O); note that not all fields can be used for sorting. You can toggle threading on/off through M-x mu4e-headers-toggle-property or Pt. For both of these functions, unless you provide a prefix argument (C-u), the current search is updated immediately using the new parameters. You can toggle full-search (Searching) through M-x mu4e-headers-toggle-property as well; or Pf.

Note that with threading enabled, the sorting is exclusively by date, regardless of the column clicked.

If you want to change the defaults for these settings, you can use the variables mu4e-search-sort-field and mu4e-search-show-threads, as well as mu4e-search-change-sorting to change the sorting of the current search results.

Custom headers
==============

Sometimes the normal headers that mu4e offers (Date, From, To, Subject, etc.) may not be enough. For these cases, mu4e offers custom headers in both the headers-view and the message-view.

You can do so by adding a description of your custom header to mu4e-header-info-custom, which is a list of custom headers.

Let's look at an example --- suppose we want to add a custom header that shows the number of recipients for a message, i.e., the sum of the number of recipients in the To: and Cc: fields. Let's further suppose that our function takes a message-plist as its argument (Message functions).

     (add-to-list 'mu4e-header-info-custom
       '(:recipnum .
          ( :name "Number of recipients"  ;; long name, as seen in the message-view
            :shortname "Recip#"           ;; short name, as seen in the headers view
            :help "Number of recipients for this message" ;; tooltip
            :function (lambda (msg)
               (format "%d"
                 (+ (length (mu4e-message-field msg :to))
                    (length (mu4e-message-field msg :cc))))))))

Or, let's get the full mailing-list name:

     (add-to-list 'mu4e-header-info-custom
      '(:full-mailing-list .
          ( :name "Mailing-list"               ;; long name, as seen in the message-view
            :shortname "ML"                    ;; short name, as seen in the headers view
            :help "Full name for mailing list" ;; tooltip
            :function (lambda (msg)
                (or (mu4e-message-field msg :mailing-list) "")))))

You can then add the custom header to your mu4e-headers-fields, just like the built-in headers. After evaluation, your headers-view should include a new header Recip# with the number of recipients, and/or ML with the full mailing-list name.

This function can be used in both the headers-view and the message-view; if you need something specific for one of these, you can check for the mode in your function, or create separate functions.

Actions
=======

mu4e-headers-action (a) lets you pick custom actions to perform on the message at point. You can specify these actions using the variable mu4e-headers-actions. See Actions for the details.

mu4e defines some default actions. One of those is for capturing a message: a c `captures' the current message. Next, when you're editing some message, you can include the previously captured message as an attachment, using mu4e-compose-attach-captured-message. See mu4e-actions.el in the mu4e source distribution for more example actions.

Buffer display
==============

By default, mu4e will attempt to manage the display of its own buffers. For headers and message views, the variable mu4e-split-view is mu4e's built-in way to decide how and where they are shown.

Split view
----------

You can control how mu4e displays its buffers, including the Headers view and the Message view, by customizing mu4e-split-view. There are several options available:

  * horizontal (this is the default): display the message view below the header view. Use mu4e-headers-visible-lines the set the number of lines shown (default: 8).

  * vertical: display the message view on the right side of the header view. Use mu4e-headers-visible-columns to set the number of visible columns (default: 30).

  * single-window: single window mode. Single-window mode tries to minimize mu4e window operations (opening, killing, resizing, etc) and buffer changes, while still retaining the view and headers buffers. In addition, it replaces mu4e's main view with a minibuffer-prompt containing the same information.

  * anything else: prefer reusing the same window, where possible.

Note that using a window-returning function for mu4e-split-view is no longer supported, instead you can use display-buffer-alist, see the section on further display customization.

Some useful key bindings in the split view:

  * C-+ and C--: interactively change the number of columns or headers shown

  * You can change the selected window from the headers-view to the message-view and vice-versa with mu4e-select-other-view, bound to y

Further customization
---------------------

However, mu4e's display rules are provisional; you can override them easily by customizing display-buffer-alist, which governs how Emacs -- and thus mu4e -- must display your buffers.

That means you can instruct mu4e to place message views in separate tabs or frames, if you so desire.

Display Customization Example
-----------------------------

You do not need to configure mu4e-split-view for this to work. In the absence of explicit rules to the contrary, mu4e will fall back on the value you have set in mu4e-split-view.

Here is an example that displays the headers buffer in a side window to the right. It occupies half of the width of the frame.

     (add-to-list 'display-buffer-alist
       '(("\\*mu4e-headers\\*" display-buffer-in-side-window
         (side . right)
         (window-width . 0.5)))

You can type C-x w s to toggle the side windows to hide or show them at will.

Note that you may need to customize mu4e-view-rendered-hook as well; by default it contains mu4e-resize-linked-headers-window but you can set it to nil if you want to handle manually (through display-buffer-alist.

The message view
****************

This chapter discusses the message view; this is new (since version 1.6) message view, based on Gnus' Article Mode, which replaces the older one.

After selecting a message in the Headers view, it appears in a message view window, which shows the message headers, followed by the message body. Its major mode is mu4e-view-mode, which derives from gnus-article-mode.

Overview
========

An example message view:

    From: randy@epiphyte.com
    To: julia@eruditorum.org
    Subject: Re: some pics
    Flags: seen, attach
    Date: Thu, 11 Feb 2021 12:59:30 +0200 (4 weeks, 3 days, 21 hours ago)
    Maildir: /inbox
    Attachments: [2. image/jpeg; DSCN4961.JPG]... [3. image/jpeg; DSCN4962.JPG]...

    Hi Julia,

    Some pics from our trip to Cerin Amroth. Enjoy!

    All the best,
    Randy.

    On Sun 21 Dec 2003 09:06:34 PM EET, Julia wrote:

    [....]

Some notes:

  * The variable mu4e-view-fields determines the header fields to be shown; see mu4e-header-info for a list of built-in fields. Apart from the built-in fields, you can also create custom fields using mu4e-header-info-custom; see MSGV Custom headers.

  * For search-related operations, see Searching.

  * You can scroll down the message using SPC; if you do this at the end of a message,it automatically takes you to the next one. If you want to prevent this behavior, set mu4e-view-scroll-to-next to nil.

Keybindings
===========

You can find most things you can do with this message in the View menu, or by using the keyboard; the default bindings are:

key          description
==============================================================
n,p          view the next, previous message
],[          move to the next, previous unread message
y            select the headers view (if it's visible)

RET          scroll down
M-RET        open URL at point / attachment at point

SPC          scroll down, if at end, move to next message
S-SPC        scroll up

searching
---------
s            search
S            edit last query
/            narrow the search
b            search bookmark
B            edit bookmark before search
j            jump to maildir

O            change sort order
P            toggle search property

M-left       previous query
M-right      next query

marking messages
----------------
d            mark for moving to the trash folder
=            mark for removing trash flag ('untrash')
DEL,D        mark for complete deletion
m            mark for moving to another maildir folder
r            mark for refiling
+,-          mark for flagging/unflagging

u            unmark message at point
U            unmark *all* messages

%            mark based on a regular expression
T,t          mark whole thread, subthread

<insert>,*   mark for 'something' (decide later)
#            resolve deferred 'something' marks

x            execute actions for the marked messages

composition
-----------
R,F,C        reply/forward/compose
E            edit (only allowed for draft messages)

actions
-------
g            go to (visit) numbered URL (using `browse-url')
(or: <mouse-1> or M-RET with point on url)
C-u g visits multiple URLs
f            fetch (download )the numbered URL.
C-u f fetches multiple URLs
k            save the numbered URL in the kill-ring.
C-u k saves multiple URLs

e            extract (save) one or more attachments (asks for numbers)
(or: <mouse-2> or S-RET with point on attachment)
a            execute some custom action on the message
A            execute some custom action on the message's MIME-parts

misc
----
z, Z         detach (or reattach) a message view to a headers buffer
.            show the raw message view. 'q' takes you back.
C-+,C--      increase / decrease the number of headers shown
H            get help
C-S-u        update mail & reindex
q            leave the message view

Furthermore, a number of keybindings are available through minor modes:

  * Context; see Contexts.

For the marking commands, please refer to Marking messages.

Reading rich-text messages
==========================

These days, many e-mail messages contain rich-text (typically, HTML); either as an alternative to a text-only version, or even as the only option.

By default, mu4e tries to display the 'richest' option, which is the last MIME-part of the alternatives. You can customize this to prefer the text version, if available, with something like the following in your configuration (and see the docstring for mm-discouraged-alternatives for details):

     (with-eval-after-load "mm-decode"
       (add-to-list 'mm-discouraged-alternatives "text/html")
       (add-to-list 'mm-discouraged-alternatives "text/richtext"))

When displaying rich-text messages inline, mu4e (through gnus) uses the shr built-in HTML-renderer. If you're using a dark color theme, and the messages are hard to read, it can help to change the luminosity, e.g.:

     (setq shr-color-visible-luminance-min 80)

Note that you can switch between the HTML and text versions by clicking on the relevant part in the messages headers; you can make it even clearer by indicating them in the message itself, using:

     (setq gnus-unbuttonized-mime-types nil)

Inline images
-------------

When you run Emacs in graphical mode, by default images attached to messages are shown inline in the message view buffer.

To disable this, set gnus-inhibit-images to t.  By default, external images in HTML are not retrieved from external URLs because they can be used to track you.

Apart from that, you can also control whether to load remote images; since loading remote images is often used for privacy violations, by default this is not allowed.

You can specify what URLs to block by setting gnus-blocked-images to a regular expression or to a function that will receive a single parameter which is not meaningful for mu4e.

For example, to enable images in Github notifications, you could use the following:

     (setq gnus-blocked-images
        (lambda(&optional _ignore)
          (if (mu4e-message-contact-field-matches
              (mu4e-message-at-point) :from "notifications@github.com")
             nil ".")))

mu4e inherits the default gnus-blocked-images from Gnus and ensures that it works with mu4e too. However, mu4e is not Gnus, so if you have Gnus-specific settings for gnus-blocked-images, you should verify that they have the desired effect in mu4e as well.

Custom headers
==============

Sometimes the normal headers (Date, From, To, Subject, etc.) may not be enough. For these cases, mu4e offers custom headers in both the headers-view and the message-view.

See HV Custom headers for an example of this; the difference for the message-view is that you should add your custom header to mu4e-view-fields rather than mu4e-headers-fields.

Actions
=======

You can perform custom functions (``actions'') on messages and their attachments. For a general discussion on how to define your own, see Actions.

Message actions
---------------

mu4e-view-action (a) lets you pick some custom action to perform on the current message. You can specify these actions using the variable mu4e-view-actions; mu4e defines a number of example actions.

MIME-part actions
-----------------

MIME-part actions allow you to act upon MIME-parts in a message - such as attachments.  For now, these actions are defined and documented in mu4e-view-mime-part-actions.

Detaching and reattaching messages
==================================

You can have multiple message views, but you must rename the view buffer and detach it to stop mu4e from reusing it when you navigate up or down in the headers buffer. If you have several view buffers attached to a headers view, then mu4e may pick one at random when it has to choose which one to display a message in.

To detach the message view from its linked headers buffer, type z. A message will appear saying it is detached (or warn you if it is already detached.)

Detached buffers are static; they cannot change the displayed message, and no headers buffer will use a detached buffer to display its messages. You can reattach a buffer to an live headers buffer by typing Z.

You can freely rename a message view buffer -- such as with C-x x r -- if you want multiple, open messages.

Detached messages are often useful for workflows involving lots of simultaneous messages.

You can tear off the window a message is in and place it in a new tab by typing C-x w ^ f. You can also detach a window and put it in its own tab with C-x w ^ t.

The editor view
***************

Writing e-mail messages takes place in the Editor View. mu4e's editor view builds on top of Gnus' message-mode. Most of the message-mode functionality is available, as well some mu4e-specifics. Its major mode is mu4e-compose-mode.

Overview
========

    From: Rupert the Monkey <rupert@example.com>
    To: Wally the Walrus <wally@example.com>
    Subject: Re: Eau-qui d'eau qui?
    --text follows this line--

    On Mon 16 Jan 2012 10:18:47 AM EET, Wally the Walrus wrote:

    > Hi Rupert,
    >
    > Dude - how are things?
    >
    > Later -- wally.

Keybindings
===========

mu4e's editor view derives from Gnus' message editor and shares most of its keybindings. Here are some of the more useful ones (you can use the menu to find more):

key          description
---          -----------
C-c C-c      send message
C-c C-d      save to drafts and leave
C-c C-k      kill the message buffer (the message remains in the draft folder)
C-c C-a      attach a file (pro-tip: drag & drop works as well)
C-c C-;      switch the context

(mu4e-specific)
C-S-u        update mail & reindex

Address autocompletion
======================

mu4e supports (GNU Emacs 24.4 or higher is required) autocompleting addresses when composing e-mail messages. mu4e uses the e-mail addresses from the messages you sent or received as the source for this. Address auto-completion is enabled by default; if you want to disable it for some reason, set mu4e-compose-complete-addresses to nil.

Emacs 24 also supports cycling through the alternatives. When there are more than 5 matching addresses, they are shown in a *Completions* buffer. Once the number of matches gets below this number, one is inserted in the address field and you can cycle through the alternatives using TAB.

Limiting the number of addresses
--------------------------------

If you have a lot of mail, especially from mailing lists and the like, there can be a lot of e-mail addresses, many of which may not be very useful when auto-completing. For this reason, mu4e attempts to limit the number of e-mail addresses in the completion pool by filtering out the ones that are not likely to be relevant. The following variables are available for tuning this:

  * mu4e-compose-complete-only-personal --- when set to t, only consider addresses that were seen in personal messages --- that is, messages in which one of my e-mail addresses was seen in one of the address fields. This is to exclude mailing list posts. You can define what is considered `my e-mail address' using the --my-address parameter to mu init.

  * mu4e-compose-complete-only-after --- only consider e-mail addresses last seen after some date. Parameter is a string, parseable by org-parse-time-string. This excludes old e-mail addresses. The default is "2010-01-01", i.e., only consider e-mail addresses seen since the start of 2010.

  * mu4e-compose-complete-max -- the maximum number of contacts to use. This adds a hard limit to the 2000 (default) contacts; those are sorted by recency /frequency etc. so should include the ones you most likely need.

  * mu4e-contact-process-function --- a function to rewrite or exclude certain addresses.

Compose hooks
=============

If you want to change some setting, or execute some custom action before message composition starts, you can define a hook function. mu4e offers two hooks:

  * mu4e-compose-pre-hook: this hook is run before composition starts; if you are composing a reply, forward a message, or edit an existing message, the variable mu4e-compose-parent-message points to the message being replied to, forwarded or edited, and you can use mu4e-message-field to get the value of various properties (and see Message functions).

  * mu4e-compose-mode-hook: this hook is run just before composition starts, when the whole buffer has already been set up. This is a good place for editing-related settings. mu4e-compose-parent-message (see above) is also at your disposal.

Let's look at some examples. First, suppose we want to set the From:-address for a reply message based on the receiver of the original:

     ;; 1) messages to me@foo.example.com should be replied with From:me@foo.example.com
     ;; 2) messages to me@bar.example.com should be replied with From:me@bar.example.com
     ;; 3) all other mail should use From:me@cuux.example.com
     (add-hook 'mu4e-compose-pre-hook
       (defun my-set-from-address ()
         "Set the From address based on the To address of the original."
         (let ((msg mu4e-compose-parent-message)) ;; msg is shorter...
           (when msg
             (setq user-mail-address
               (cond
                 ((mu4e-message-contact-field-matches msg :to "me@foo.example.com")
                   "me@foo.example.com")
                 ((mu4e-message-contact-field-matches msg :to "me@bar.example.com")
                   "me@bar.example.com")
                 (t "me@cuux.example.com")))))))

Secondly, as mentioned, mu4e-compose-mode-hook is especially useful for editing-related settings. For example:

     (add-hook 'mu4e-compose-mode-hook
       (defun my-do-compose-stuff ()
         "My settings for message composition."
         (set-fill-column 72)
         (flyspell-mode)))

This hook is also useful for adding headers or changing headers, since the message is fully formed when this hook runs. For example, to add a Bcc:-header, you could add something like the following, using message-add-header from message-mode.

     (add-hook 'mu4e-compose-mode-hook
       (defun my-add-bcc ()
         "Add a Bcc: header."
         (save-excursion (message-add-header "Bcc: me@example.com\n"))))

Or to something context-specific:

     (add-hook 'mu4e-compose-mode-hook
       (lambda()
         (let* ((ctx (mu4e-context-current))
                 (name (if ctx (mu4e-context-name ctx))))
           (when name
             (cond
               ((string= name "account1")
                 (save-excursion (message-add-header "Bcc: account1@example.com\n")))
               ((string= name "account2")
                 (save-excursion (message-add-header "Bcc: account2@example.com\n"))))))))

For a more general discussion about extending mu4e, see Extending mu4e.

Signing and encrypting
======================

Signing and encrypting of messages is possible using emacs-mime, most easily accessed through the Attachments-menu while composing a message, or with M-x mml-secure-message-encrypt-pgp, M-x mml-secure-message-sign-pgp.

Important note: the messages are encrypted when they are sent: this means that draft messages are not encrypted. So if you are using e.g. offlineimap or mbsync to synchronize with some remote IMAP-service, make sure the drafts folder is not in the set of synchronized folders, for obvious reasons.

Queuing mail
============

If you cannot send mail right now, for example because you are currently offline, you can queue the mail, and send it when you have restored your internet connection. You can control this from the Main view.

To allow for queuing, you need to tell smtpmail where you want to store the queued messages. For example:

     (setq smtpmail-queue-mail t  ;; start in queuing mode
       smtpmail-queue-dir   "~/Maildir/queue/cur")

For convenience, we put the queue directory somewhere in our normal maildir. If you want to use queued mail, you should create this directory before starting mu4e. The mu mkdir command may be useful here, so for example:

  $ mu mkdir ~/Maildir/queue
  $ touch ~/Maildir/queue/.noindex

The file created by the touch command tells mu to ignore this directory for indexing, which makes sense since it contains smtpmail meta-data rather than normal messages; see the mu-mkdir and mu-index man-pages for details.

Warning: when you switch on queued-mode, your messages won't reach their destination until you switch it off again; so, be careful not to do this accidentally!

Message signatures
==================

Message signatures are the standard footer blobs in e-mail messages where you can put in information you want to include in every message. The text to include is set with mu4e-compose-signature.

If you don't want to include this automatically with each message, you can set mu4e-compose-signature-auto-include to nil; you can then still include the signature manually, using the function message-insert-signature, typically bound to C-c C-w.

Other settings
==============

  * If you want use mu4e as Emacs' default program for sending mail, see Default email client.

  * Normally, mu4e buries the message buffer after sending; if you want to kill the buffer instead, add something like the following to your configuration:

          (setq message-kill-buffer-on-exit t)

  * If you want to exclude your own e-mail address when ``replying to all'', set mu4e-compose-dont-reply-to-self to t. In order for this to work properly you need to pass your address to mu init --my-address= at database initialization time.

Searching
*********

mu4e is fully search-based: even if you `jump to a folder', you are executing a query for messages that happen to have the property of being in a certain folder (maildir).

Normally, queries return up to mu4e-headers-results-limit (default: 500) results. That is usually more than enough, and makes things significantly faster. Sometimes, however, you may want to show all results; you can enable this with M-x mu4e-headers-toggle-property, or by customizing the variable mu4e-headers-full-search. This applies to all search commands.

You can also influence the sort order and whether threads are shown or not; see Sorting and threading.

Queries
=======

mu4e queries are the same as the ones that mu find understands (with the caveat that command-line queries are subject to the shell's interpretation before mu sees them). You can consult the mu-query man page for the details.

Additionally, mu4e supports TAB-completion for queries. There there is completion for all search keywords such as and, from:, or date: and also for certain values, i.e., the possible values for flag:, prio:, mime:, and maildir:.

Let's look at some examples here.

  * Get all messages regarding bananas:
     bananas

  * Get all messages regarding bananas from John with an attachment:
     from:john and flag:attach and bananas

  * Get all messages with subject wombat in June 2017
     subject:wombat and date:20170601..20170630

  * Get all messages with PDF attachments in the /projects folder
     maildir:/projects and mime:application/pdf

  * Get all messages about Rupert in the /Sent Items folder. Note that maildirs with spaces must be quoted.
     "maildir:/Sent Items" and rupert

  * Get all important messages which are signed:
     flag:signed and prio:high

  * Get all messages from Jim without an attachment:
     from:jim and not flag:attach

  * Get all messages with Alice in one of the contacts-fields (to, from, cc, bcc):
     contact:alice

  * Get all unread messages where the subject mentions Ångström: (search is case-insensitive and accent-insensitive, so this matches Ångström, angstrom, aNGstrøM, ...)
     subject:Ångström and flag:unread

  * Get all unread messages between Mar-2012 and Aug-2013 about some bird:
     date:20120301..20130831 and nightingale and flag:unread

  * Get today's messages:
     date:today..now

  * Get all messages we got in the last two weeks regarding emacs:
     date:2w.. and emacs

  * Get messages from the Mu mailing list:
     list:mu-discuss.googlegroups.com

     Note --- in the Headers view you may see the `friendly name' for a list; however, when searching you need the real name. You can see the real name for a mailing list from the friendly name's tool-tip.

  * Get messages with a subject soccer, Socrates, society, ...; note that the `*'-wildcard can only appear as a term's rightmost character:
     subject:soc*

  * Get all messages not sent to a mailing-list:
     NOT flag:list

  * Get all mails with attachments with filenames starting with pic; note that the `*' wildcard can only appear as the term's rightmost character:
     file:pic*

  * Get all messages with PDF-attachments:
     mime:application/pdf

     Get all messages with image attachments, and note that the `*' wildcard can only appear as the term's rightmost character:
     mime:image/*

     Get all messages with files that end in .ppt; this uses the regular-expression support, which is powerful but relatively slow:
     file:/\.ppt$/

Bookmarks
=========

If you have queries that you use often, you may want to store them as bookmarks. Bookmark searches are available in the main view (see Main view), header view (see Headers view), and message view (see Message view), using (by default) the key b (M-x mu4e-search-bookmark), or B (M-x mu4e-search-bookmark-edit) which lets you edit the bookmark first.

Setting up bookmarks
--------------------

mu4e provides a number of default bookmarks. Their definition may be instructive:

     (defcustom mu4e-bookmarks
       '(( :name  "Unread messages"
           :query "flag:unread AND NOT flag:trashed"
           :key ?u)
         ( :name "Today's messages"
           :query "date:today..now"
           :key ?t)
         ( :name "Last 7 days"
           :query "date:7d..now"
           :hide-unread t
           :key ?w)
         ( :name "Messages with images"
           :query "mime:image/*"
           :key ?p))
       "List of pre-defined queries that are shown on the main screen.

     Each of the list elements is a plist with at least:
     :name  - the name of the query
     :query - the query expression
     :key   - the shortcut key.

     Optionally, you add the following:
     :hide  - if t, bookmark is hdden from the main-view and speedbar.
     :hide-unread - do not show the counts of unread/total number
      of matches for the query. This can be useful if a bookmark uses
      a very slow query. :hide-unread is implied from :hide.
     "
       :type '(repeat (plist))
       :group 'mu4e)

You can replace these or add your own items, by putting in your configuration (~/.emacs) something like:

     (add-to-list 'mu4e-bookmarks
       '( :name  "Big messages"
          :query "size:5M..500M"
          :key   ?b))

This prepends your bookmark to the list, and assigns the key b to it. If you want to append your bookmark, you can use t as the third argument to add-to-list.

In the various mu4e views, pressing b lists all the bookmarks defined in the echo area, with the shortcut key highlighted. So, to invoke the bookmark we just defined (to get the list of "Big Messages"), all you need to type is bb.

Lisp expressions or functions as bookmarks
------------------------------------------

Instead of using strings, it is also possible to use Lisp expressions as bookmarks. Either the expression evaluates to a query string or the expression is a function taking no argument that returns a query string.

For example, to get all the messages that are at most a week old in your inbox:

     (add-to-list 'mu4e-bookmarks
       '( :name  "Inbox messages in the last 7 days"
          :query (lambda () (concat "maildir:/inbox AND date:"
                 (format-time-string "%Y%m%d"
                     (subtract-time (current-time) (days-to-time 7)))))
          :key   ?w) t)

Another example where the user is prompted how many days old messages should be shown:

     (defun my/mu4e-bookmark-num-days-old-query (days-old)
       (interactive (list (read-number "Show days old messages: " 7)))
       (let ((start-date (subtract-time (current-time) (days-to-time days-old))))
         (concat "maildir:/inbox AND date:"
                 (format-time-string "%Y%m%d" start-date))))

     (add-to-list 'mu4e-bookmarks
       `(:name  "Inbox messages in the last 7 days"
         :query ,(lambda () (call-interactively 'my/mu4e-bookmark-num-days-old-query))
         :key  ?o) t)

It is defining a function to make the code more readable.

Editing bookmarks before searching
----------------------------------

There is also M-x mu4e-search-bookmark-edit (key B), which lets you edit the bookmarked query before invoking it. This can be useful if you have many similar queries, but need to change some parameter. For example, you could have a bookmark "date:today..now AND " (Not a valid search query by itself), which limits any result to today's messages.

Maildir searches
================

Maildir searches are quite similar to bookmark searches (see Bookmarks), with the difference being that the target is always a maildir --- maildir queries provide a `traditional' folder-like interface to a search-based e-mail client. By default, maildir searches are available in the Main view, Headers view, and Message view, with the key j (mu4e-jump-to-maildir). If a prefix argument is given, the maildir query can be refined before execution.

Setting up maildir shortcuts
----------------------------

You can search for maildirs like any other message property (e.g. with a query like maildir:/myfolder), but since it is so common, mu4e offers a shortcut for this.

For this to work, you need to set the variable mu4e-maildir-shortcuts to the list of maildirs you want to have quick access to, for example:

     (setq mu4e-maildir-shortcuts
       '( (:maildir "/inbox"     :key  ?i)
          (:maildir "/archive"   :key  ?a)
          (:maildir "/lists"     :key  ?l)
          (:maildir "/work"      :key  ?w)
          (:maildir "/sent"      :key  ?s)
          (:maildir "/lists/project/project_X" :key ?x :name "Project X")))

This sets i as a shortcut for the /inbox folder --- effectively a query maildir:/inbox. There is a special shortcut o or / for other (so don't use those for your own shortcuts!), which allows you to choose from all maildirs that you have. There is support for autocompletion; note that the list of maildirs is determined when mu4e starts; if there are changes in the maildirs while mu4e is running, you need to restart mu4e. Optionally, you can specify a name to be displayed in the main view.

Each of the folder names is relative to your top-level maildir directory; so if you keep your mail in ~/Maildir, /inbox would refer to ~/Maildir/inbox. With these shortcuts, you can jump around your maildirs (folders) very quickly --- for example, getting to the /lists folder only requires you to type jl, then change to /work with jw.

While in queries you need to quote folder names (maildirs) with spaces in them, you should not quote them when used in mu4e-maildir-shortcuts, since mu4e does that automatically for you.

The very same shortcuts are used by M-x mu4e-mark-for-move (default shortcut m); so, for example, if you want to move a message to the /archive folder, you can do so by typing ma.

Other search functionality
==========================

Navigating through search queries
---------------------------------

You can navigate through previous/next queries using mu4e-headers-query-prev and mu4e-headers-query-next, which are bound to M-left and M-right, similar to what some web browsers do.

mu4e tries to be smart and not record duplicate queries. Also, the number of queries remembered has a fixed limit, so mu4e won't use too much memory, even if used for a long time. However, if you want to forget previous/next queries, you can use M-x mu4e-headers-forget-queries.

Narrowing search results
------------------------

It can be useful to narrow existing search results, that is, to add some clauses to the current query to match fewer messages.

For example, suppose you're looking at some mailing list, perhaps by jumping to a maildir (M-x mu4e-headers-jump-to-maildir, j) or because you followed some bookmark (M-x mu4e-search-bookmark, b). Now, you want to narrow things down to only those messages that have attachments.

This is when M-x mu4e-search-narrow (/) comes in handy. It asks for an additional search pattern, which is appended to the current search query, in effect getting you the subset of the currently shown headers that also match this extra search pattern. \ takes you back to the previous query, so, effectively `widens' the search. Technically, narrowing the results of query x with expression y implies doing a search (x) AND (y).

Note that messages that were not in your original search results because of mu4e-search-results-limit may show up in the narrowed query.

Including related messages
--------------------------

It can be useful to not only show the messages that directly match a certain query, but also include messages that are related to these messages. That is, messages that belong to the same discussion threads are included in the results, just like e.g. Gmail does it. You can enable this behavior by setting mu4e-search-include-related to t, and you can toggle between including/not-including with W.

Be careful though when e.g. deleting ranges of messages from a certain folder --- the list may now also include messages from other folders.

Skipping duplicates
-------------------

Another useful feature is skipping of duplicate messages. When you have copies of messages, there's usually little value in including more than one in search results. A common reason for having multiple copies of messages is the combination of Gmail and offlineimap, since that is the way the labels / virtual folders in Gmail are represented. You can enable skipping duplicates by setting mu4e-search-skip-duplicates to t, and you can toggle between the skipping/not skipping with V.

Note, messages are considered duplicates when they have the same Message-Id.

Marking
*******

In mu4e, the common way to do things with messages is a two-step process - first you mark them for a certain action, then you execute (x) those marks. This is similar to the way dired operates. Marking can happen in both the Headers view and the Message view.

Marking messages
================

There are multiple ways to mark messages:

  * message at point: you can put a mark on the message-at-point in either the Headers view or Message view

  * region: you can put a mark on all messages in the current region (selection) in the Headers view

  * pattern: you can put a mark on all messages in the Headers view matching a certain pattern with M-x mu4e-headers-mark-pattern (%)

  * thread/subthread: You can put a mark on all the messages in the thread/subthread at point with M-x mu4e-headers-mark-thread and M-x mu4e-headers-mark-subthread, respectively

What to mark for
================

mu4e supports a number of marks:

mark for/as  | keybinding  | description
-------------+-------------+------------------------------
'something'  | *, <insert> | mark now, decide later
delete       | D, <delete> | delete
flag         | +           | mark as 'flagged' ('starred')
move         | m           | move to some maildir
read         | !           | mark as read
refile       | r           | mark for refiling
trash        | d           | move to the trash folder
untrash      | =           | remove 'trash' flag
unflag       | -           | remove 'flagged' mark
unmark       | u           | remove mark at point
unmark all   | U           | remove all marks
unread       | ?           | marks as unread
action       | a           | apply some action

After marking a message, the left-most columns in the headers view indicate the kind of mark. This is informative, but if you mark many (say, thousands) messages, this slows things down significantly (this uses an Emacs feature called overlays, which are slow when used a lot in a buffer). For this reason, you can disable this by setting mu4e-headers-show-target to nil.

something is a special kind of mark; you can use it to mark messages for `something', and then decide later what the `something' should be (This kind of `deferred marking' is similar to the facility in dired, midnight commander (https://www.midnight-commander.org/) and the like, and uses the same key binding (insert).)  Later, you can set the actual mark using M-x mu4e-mark-resolve-deferred-marks (#). Alternatively, mu4e will ask you when you try to execute the marks (x).

Executing the marks
===================

After you have marked some messages, you can execute them with x (M-x mu4e-mark-execute-all).

A hook, mu4e-mark-execute-pre-hook, is available which is run right before execution of each mark. The hook is called with two arguments, the mark and the message itself.

Trashing messages
=================

For regular mailboxes, trashing works like other marks: when executed, the message is flagged as trashed.  Depending on your mailbox provider, the trash flag is used to automatically move the message to the trash folder (mu4e-trash-folder) for instance.

Some mailboxes behave differently however and they don't interpret the trash flag.  In cases like Gmail, the message must be moved to the trash folder and the trash flag must not be used.

Leaving the headers buffer
==========================

When you quit or update a headers buffer that has marked messages (for example, by doing a new search), mu4e asks you what to do with them, depending on the value of the variable mu4e-headers-leave-behavior --- see its documentation.

Built-in marking functions
==========================

Some examples of mu4e's built-in marking functions.

  * Mark the message at point for trashing: press d

  * Mark all messages in the buffer as unread: press C-x h o

  * Delete the messages in the current thread: press T D

  * Mark messages with a subject matching ``hello'' for flagging: press % s hello RET.

Custom mark functions
=====================

Sometimes, the built-in functions to mark messages may not be sufficient for your needs. For this, mu4e offers an easy way to define your own custom mark functions. You can choose one of the custom marker functions by pressing & in the Headers view and Message view.

Custom mark functions are to be appended to the list mu4e-headers-custom-markers. Each of the elements of this list ('markers') is a list with two or three elements:

 1. The name of the marker --- a short string describing this marker. The first character of this string determines its shortcut, so these should be unique. If necessary, simply prefix the name with a unique character.

 2. a predicate function, taking two arguments msg and param. msg is the message plist (see Message functions) and param is a parameter provided by the third of the marker elements (see the next item). The predicate function should return non-nil if the message matches.

 3. (optionally) a function that is evaluated once, and the result is passed as a parameter to the predicate function. This is useful when user-input is needed.

Let's look at an example: suppose we want to match all messages that have more than n recipients --- we could do this with the following recipe:

     (add-to-list 'mu4e-headers-custom-markers
       '("More than n recipients"
          (lambda (msg n)
            (> (+ (length (mu4e-message-field msg :to))
                 (length (mu4e-message-field msg :cc))) n))
          (lambda ()
            (read-number "Match messages with more recipients than: "))) t)

After evaluating this expression, you can use it by pressing & in the headers buffer to select a custom marker function, and then M to choose this particular one (M because it is the first character of the description).

As you can see, it's not very hard to define simple functions to match messages. There are more examples in the defaults for mu4e-headers-custom-markers; see mu4e-headers.el and see Extending mu4e for general information about writing your own functions.

Adding a new kind of mark
=========================

It is possible to configure new marks. To do so, one can add entries in the list mu4e-marks. Such an element must have the following form:

     (SYMBOL
       :char STRING
       :prompt STRING
       :ask-target (lambda () TARGET)
       :dyn-target (lambda (TARGET MSG) DYN-TARGET)
       :show-target (lambda (DYN-TARGET) STRING)
       :action (lambda (DOCID MSG DYN-TARGET) nil))

The symbol can be any symbol, except for 'unmark and 'something, which are reserved. The rest is a plist with the following elements:

  * :char --- the character to display in the headers view.

  * :prompt --- the prompt to use when asking for marks (used for example when marking a whole thread).

  * :ask-target --- a function run once per bulk-operation, and thus suitable for querying the user about a target for move-like marks. If nil, the TARGET passed to :dyn-target is nil.

  * :dyn-target --- a function run once per message (The message is passed as MSG to the function). This function allows to compute a per-message target, for refile-like marks. If nil, the DYN-TARGET passed to the :action is the TARGET obtained as above.

  * :show-target --- how to display the target in the headers view. If :show-target is nil the DYN-TARGET is shown (and DYN-TARGET must be a string).

  * :action --- the action to apply on the message when the mark is executed.

As an example, suppose we would like to add a mark for tagging messages (GMail-style), then we can run the following code (after loading mu4e):

     (add-to-list 'mu4e-marks
       '(tag
          :char       "g"
          :prompt     "gtag"
          :ask-target (lambda () (read-string "What tag do you want to add?"))
          :action      (lambda (docid msg target)
                         (mu4e-action-retag-message msg (concat "+" target)))))

As another example, suppose we would like to ``archive and mark read'' a message (GMail-style), then we can run the following code (after loading mu4e):

     (add-to-list 'mu4e-marks
       '(archive
          :char       "A"
          :prompt     "Archive"
          :show-target (lambda (target) "archive")
          :action      (lambda (docid msg target)
                         ;; must come before proc-move since retag runs
                         ;; 'sed' on the file
                         (mu4e-action-retag-message msg "-\\Inbox")
                         (mu4e--server-move docid nil "+S-u-N"))))

Adding to mu4e-marks list allows to use the mark in bulk operations (for example when tagging a whole thread), but does not bind the mark to a key to use at the top-level. This must be done separately. In our example:

     (mu4e~headers-defun-mark-for tag)
     (mu4e~headers-defun-mark-for archive)
     (define-key mu4e-headers-mode-map (kbd "g") 'mu4e-headers-mark-for-tag)
     (define-key mu4e-headers-mode-map (kbd "A") 'mu4e-headers-mark-for-archive)

Contexts
********

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.

The mu4e-context system is a mu4e-specific mechanism to allow for that; users can define different contexts corresponding with groups of setting and either manually switch between them, or let mu4e determine the right context based on some user-provided function.

Note that there are a number of existing ways to switch accounts in mu4e, for example using the method described in the Tips and Tricks section of this manual. Those still work --- but the new mechanism has the benefit of being a core part of mu4e, thus allowing for deeper integration.

What are contexts
=================

Let's see what's contained in a context. Most of it is optional.

A mu4e-context is Lisp object with the following members:

  * name: the name of the context, e.g. work or private

  * vars: an association-list (alist) of variable settings for this account.

  * enter-func: an (optional) function that takes no parameter and is invoked when entering the context. You can use this for extra setup etc.

  * leave-func: an (optional) function that takes no parameter and is invoked when leaving the context. You can use this for clearing things up.

  * match-func: an (optional) function that takes an MSG message plist as argument, and returns non-nil if this context matches the situation. mu4e uses the first context that matches, in a couple of situations:

       * when starting mu4e to determine the starting context; in this case, MSG is nil. You can use e.g. the host you're running or the time of day to determine which context matches.

       * before replying to or forwarding a message with the given message plist as parameter, or nil when composing a brand new message. The function should return t when this context is the right one for this message, or nil otherwise.

       * when determining the target folders for deleting, refiling etc; see Contexts and special folders.

mu4e uses a variable mu4e-contexts, which is a list of such objects.

Context policies
================

When you have defined contexts and you start mu4e it decides which context to use based on the variable mu4e-context-policy; similarly, when you compose a new message, the context is determined using mu4e-compose-context-policy.

For both of these, you can choose one of the following policies:

  * a symbol always-ask: unconditionally ask the user what context to pick.

The other choices only apply if none of the contexts match (i.e., none of the contexts' match-functions returns t). We have the following options:

  * a symbol ask: ask the user if mu4e can't figure things out the context by itself (through the match-function). This is a good policy if there are no match functions, or if the match functions don't cover all cases.

  * a symbol ask-if-none: if there's already a context, don't change it; otherwise, ask the user.

  * a symbol pick-first: pick the first (default) context. This is a good choice if you want to specify context for special case, and fall back to the first one if none match.

  * nil: don't change the context; this is useful if you don't change contexts very often, and e.g. manually changes contexts with M-x mu4e-context-switch.

You can easily switch contexts manually using the ; key from the main screen, or by pressing C-c ; when drafting a message using the editor view.

Contexts and special folders
============================

As we discussed in Folders and Dynamic folders, mu4e recognizes a number of special folders: mu4e-sent-folder, mu4e-drafts-folder, mu4e-trash-folder and mu4e-refile-folder.

When you have a headers-buffer with messages that belong to different contexts (say, a few different accounts), it is desirable for each of them to use the specific folders for their own context --- so, for instance, if you trash a message, it needs to go to the trash-folder for the account it belongs to, which is not necessarily the current context.

To make this easy to do, whenever mu4e needs to know the value for such a special folder for a given message, it tries to determine the appropriate context using mu4e-context-determine (and policy nil; see Context policies). If it finds a matching context, it let-binds the vars for that account, and then determines the value for the folder. It does not, however, call the enter-func or leave-func, since we are not really switching contexts.

In practice, this means that as long as each of the accounts has a good match-func, all message operations automatically find the appropriate folders.

Example
=======

Let's explain how contexts work by looking at an example. We define two contexts, `Private' and `Work' for a fictional user Alice Derleth.

Note that in this case, we automatically switch to the first context when starting; see the discussion in the previous section.

      (setq mu4e-contexts
         `( ,(make-mu4e-context
               :name "Private"
               :enter-func (lambda () (mu4e-message "Entering Private context"))
               :leave-func (lambda () (mu4e-message "Leaving Private context"))
               ;; we match based on the contact-fields of the message
               :match-func (lambda (msg)
                             (when msg
                               (mu4e-message-contact-field-matches msg
                                 :to "aliced@home.example.com")))
               :vars '( ( user-mail-address	    . "aliced@home.example.com"  )
                        ( user-full-name	    . "Alice Derleth" )
                        ( message-user-organization . "Homebase" )
                        ( mu4e-compose-signature .
                          (concat
                            "Alice Derleth\n"
                            "Lauttasaari, Finland\n"))))
            ,(make-mu4e-context
               :name "Work"
               :enter-func (lambda () (mu4e-message "Switch to the Work context"))
               ;; no leave-func
               ;; we match based on the maildir of the message
               ;; this matches maildir /Arkham and its sub-directories
               :match-func (lambda (msg)
                             (when msg
                               (string-match-p "^/Arkham" (mu4e-message-field msg :maildir))))
               :vars '( ( user-mail-address	     . "aderleth@miskatonic.example.com" )
                        ( user-full-name	     . "Alice Derleth" )
                        ( message-user-organization . "Miskatonic University" )
                        ( mu4e-compose-signature  .
                          (concat
                            "Prof. Alice Derleth\n"
                            "Miskatonic University, Dept. of Occult Sciences\n"))))

            ,(make-mu4e-context
               :name "Cycling"
               :enter-func (lambda () (mu4e-message "Switch to the Cycling context"))
               ;; no leave-func
               ;; we match based on the maildir of the message; assume all
               ;; cycling-related messages go into the /cycling maildir
               :match-func (lambda (msg)
                             (when msg
                               (string= (mu4e-message-field msg :maildir) "/cycling")))
               :vars '( ( user-mail-address	     . "aderleth@example.com" )
                        ( user-full-name	     . "AliceD" )
                        ( mu4e-compose-signature  . nil)))))

       ;; set `mu4e-context-policy` and `mu4e-compose-policy` to tweak when mu4e should
       ;; guess or ask the correct context, e.g.

       ;; start with the first (default) context;
       ;; default is to ask-if-none (ask when there's no context yet, and none match)
       ;; (setq mu4e-context-policy 'pick-first)

       ;; compose with the current context is no context matches;
       ;; default is to ask
       ;; (setq mu4e-compose-context-policy nil)

A couple of notes about this example:

  * You can manually switch the context use M-x mu4e-context-switch, by default bound to ; in headers, view and main mode. The current context appears in the modeline by default; see Modeline for details.

  * Normally, M-x mu4e-context-switch does not call the enter or leave functions if the 'new' context is the same as the old one. However, with a prefix-argument (C-u), you can force mu4e to invoke those function even in that case.

  * The function mu4e-context-current returns the current-context; the current context is also visible in the mode-line when in headers, view or main mode.

  * You can set any kind of variable; including settings for mail servers etc. However, settings such as mu4e-mu-home are not changeable after they have been set without quitting mu4e first.

  * leave-func (if defined) for the context we are leaving, is invoked before the enter-func (if defined) of the context we are entering.

  * enter-func (if defined) is invoked before setting the variables.

  * match-func (if defined) is invoked just before mu4e-compose-pre-hook.

  * See the variables mu4e-context-policy and mu4e-compose-context-policy to tweak what mu4e should do when no context matches (or if you always want to be asked).

  * Finally, be careful to get the quotations right --- backticks, single quotes and commas and note the '.' between variable name and its value.

Dynamic folders
***************

In Folders, we explained how you can set up mu4e's special folders:

     (setq
       mu4e-sent-folder   "/sent"       ;; sent messages
       mu4e-drafts-folder "/drafts"     ;; unfinished messages
       mu4e-trash-folder  "/trash"      ;; trashed messages
       mu4e-refile-folder "/archive")   ;; saved messages

In some cases, having such static folders may not suffice --- perhaps you want to change the folders depending on the context. For example, the folder for refiling could vary, based on the sender of the message.

To make this possible, instead of setting the standard folders to a string, you can set them to be a function that takes a message as its parameter, and returns the desired folder name. This chapter shows you how to do that. For a more general discussion of how to extend mu4e and writing your own functions, see Extending mu4e.

If you use mu4e-context, see Contexts and special folders for what that means for these special folders.

Smart refiling
==============

When refiling messages, perhaps to archive them, it can be useful to have different target folders for different messages, based on some property of those message --- smart refiling.

To accomplish this, we can set the refiling folder (mu4e-refile-folder) to a function that returns the actual refiling folder for the particular message. An example should clarify this:

     (setq mu4e-refile-folder
       (lambda (msg)
         (cond
           ;; messages to the mu mailing list go to the /mu folder
           ((mu4e-message-contact-field-matches msg :to
              "mu-discuss@googlegroups.com")
             "/mu")
           ;; messages sent directly to some spefic address me go to /private
           ((mu4e-message-contact-field-matches msg :to "me@example.com")
             "/private")
           ;; messages with football or soccer in the subject go to /football
           ((string-match "football\\|soccer"
              (mu4e-message-field msg :subject))
             "/football")
           ;; messages sent by me go to the sent folder
           ((mu4e-message-sent-by-me msg
              (mu4e-personal-addresses))
             mu4e-sent-folder)
           ;; everything else goes to /archive
           ;; important to have a catch-all at the end!
           (t  "/archive"))))

This can be very powerful; you can select some messages in the headers view, then press r, and have them all marked for refiling to their particular folders.

Some notes:

  * We set mu4e-refile-folder to an anonymous (lambda) function. This function takes one argument, a message plist (a property list describing a message). The plist corresponds to the message at point. See Message functions for a discussion on how to deal with them.

  * In our function, we use a cond control structure; the function returns the first of the clauses that matches. It's important to make the last clause a catch-all, so we always return some folder.

  * We use the convenience function mu4e-message-contact-field-matches, which evaluates to t if any of the names or e-mail addresses in a contact field (in this case, the To:-field) matches the regular expression. With mu4e version 0.9.16 or newer, the contact field can in fact be a list instead of a single value, such as '(:to :cc)'.

Other dynamic folders
=====================

Using the same mechanism, you can create dynamic sent-, trash-, and drafts-folders. The message-parameter you receive for the sent and drafts folder is the original message, that is, the message you reply to, or forward, or edit. If there is no such message (for example when composing a brand new message) the message parameter is nil.

Let's look at an example. Suppose you want a different trash folder for work-email. You can achieve this with something like:

     (setq mu4e-trash-folder
     (lambda (msg)
     ;; the 'and msg' is to handle the case where msg is nil
     (if (and msg
     (mu4e-message-contact-field-matches msg :to "me@work.example.com"))
     "/trash-work"
     "/trash")))

Good to remember:

  * The msg parameter you receive in the function refers to the original message, that is, the message being replied to or forwarded. When re-editing a message, it refers to the message being edited. When you compose a totally new message, the msg parameter is nil.

  * When re-editing messages, the value of mu4e-drafts-folder is ignored.

Actions
*******

mu4e lets you define custom actions for messages in Headers view and for both messages and attachments in Message view. Custom actions allow you to easily extend mu4e for specific needs --- for example, marking messages as spam in a spam filter or applying an attachment with a source code patch.

You can invoke the actions with key a for actions on messages, and key A for actions on attachments.

For general information extending mu4e and writing your own functions, see Extending mu4e.

Defining actions
================

Defining a new custom action comes down to writing an elisp-function to do the work. Functions that operate on messages receive a MSG parameter, which corresponds to the message at point. Something like:

     (defun my-action-func (msg)
       "Describe my message function."
       ;; do stuff
       )

Functions that operate on attachments receive a MSG parameter, which corresponds to the message at point, and an ATTACHMENT-NUM, which is the number of the attachment as seen in the message view. An attachment function looks like:

     (defun my-attachment-action-func (msg attachment-num)
       "Describe my attachment function."
       ;; do stuff
       )

After you have defined your function, you can add it to the list of actions (Instead of defining the functions separately, you can obviously also add a lambda-function directly to the list; however, separate functions are easier to change), either mu4e-headers-actions, mu4e-view-actions or mu4e-view-mime-part-actions.  The format (Note, the format of the actions has changed since version 0.9.8.4, and you must change your configuration to use the new format; mu4e warns you when you are using the old format.) of each action is a cons-cell, (DESCRIPTION . VALUE); see below for some examples. If your shortcut is not also the first character of the description, simply prefix the description with that character.

Let's look at some examples.

Headers view actions
====================

Suppose we want to inspect the number of recipients for a message in the Headers view. We add the following to our configuration:

     (defun show-number-of-recipients (msg)
       "Display the number of recipients for the message at point."
       (message "Number of recipients: %d"
         (+ (length (mu4e-message-field msg :to))
           (length (mu4e-message-field msg :cc)))))

     ;; define 'N' (the first letter of the description) as the shortcut
     ;; the 't' argument to add-to-list puts it at the end of the list
     (add-to-list 'mu4e-headers-actions
       '("Number of recipients" . show-number-of-recipients) t)

After evaluating this, a N in the headers view shows the number of recipients for the message at point.

Message view actions
====================

As another example, suppose we would like to search for messages by the sender of the message at point:

     (defun search-for-sender (msg)
       "Search for messages sent by the sender of the message at point."
       (mu4e-search
         (concat "from:"
           (mu4e-contact-email (car (mu4e-message-field msg :from))))))

     ;; define 'x' as the shortcut
     (add-to-list 'mu4e-view-actions
       '("xsearch for sender" . search-for-sender) t)

If you wonder why we use car, remember that the From:-field is a list of (:name NAME :email EMAIL) plists; so this code gets us the e-mail address of the first in the list. From:-fields rarely have more that one address.

MIME-part actions
=================

Finally, let's define a MIME-part action. As mentioned, MIME-part functions receive 2 arguments, the message and the attachment number to use.

The following example action counts the number of lines in an attachment, and defines n as its shortcut key (the n is prefixed to the description).

     (defun count-lines-in-attachment (msg attachnum)
       "Count the number of lines in an attachment."
       (mu4e-view-pipe-attachment msg attachnum "wc -l"))

     ;; defining 'n' as the shortcut
     (add-to-list 'mu4e-view-mime-part-actions
       '("ncount lines" . count-lines-in-attachment) t)

Example actions
===============

mu4e includes a number of example actions in the file mu4e-actions.el in the source distribution (see C-h f mu4e-action-TAB). For example, for viewing messages in an external web browser.

Extending mu4e
**************

mu4e is designed to be easily extensible --- that is, write your own emacs-lisp to make mu4e behave exactly as you want. Here, we provide some guidelines for doing so.

Extension points
================

There are a number of places where mu4e lets you plug in your own functions:

  * Custom functions for message header --- see HV Custom headers

  * Using message-specific folders for drafts, trash, sent messages and refiling, based on a function --- see Dynamic folders

  * Using an attachment-specific download-directory --- see the variable mu4e-attachment-dir.

  * Apply a function to a message in the headers view - see Headers view actions

  * Apply a function to a message in the message view --- see Message view actions

  * Add a new kind of mark for use in the headers view - see Adding a new kind of mark

  * Apply a function to a MIME-part --- see MIME-part actions

  * Custom function to mark certain messages --- see Custom mark functions

  * Using various mode-hooks, mu4e-compose-pre-hook (see Compose hooks), mu4e-index-updated-hook (see FAQ)

You can also write your own functions without using the above. If you want to do so, key useful functions are mu4e-message-at-point (see below), mu4e-headers-for-each (to iterate over all headers, see its docstring) and mu4e-view-for-each-part (to iterate over all parts/attachments, see its docstring). There is also mu4e-view-for-each-uri to iterate of all the URIs in the current message.

Another useful function is mu4e-headers-find-if which searches for a message matching a certain pattern; again, see its docstring.

Available functions
===================

The whole of mu4e consists of hundreds of elisp functions. However, the majority of those are for internal use only; you can recognize them easily, because they all start with mu4e~ or mu4e--. These functions make all kinds of assumptions, and they are subject to change, and should therefore not be used. The same is true for variables with the same prefix; don't touch them. Let me repeat that:
Do not use mu4e~... or mu4e-- functions or variables!

In addition, you should use functions in the right context; functions that start with mu4e-view- are only applicable to the message view, while functions starting with mu4e-headers- are only applicable to the headers view. Functions without such prefixes are applicable everywhere.

Message functions
=================

Many functions in mu4e deal with message plists (property lists). They contain information about messages, such as sender and recipient, subject, date and so on. To deal with these plists, there are a number of mu4e-message- functions (in mu4e-message.el), such as mu4e-message-field and mu4e-message-at-point, and a shortcut to combine the two, mu4e-message-field-at-point.

For example, to get the subject of the message at point, in either the headers view or the message view, you could write:

     (mu4e-message-field (mu4e-message-at-point) :subject)

Note that:

  * The contact fields (To, From, Cc, Bcc) are lists of cons-pairs (name . email); name may be nil. So, for example:

            (mu4e-message-field some-msg :to)
            ;; => (("Jack" . "jack@example.com") (nil . "foo@example.com"))

     If you are only looking for a match in this list (e.g., ``Is Jack one of the recipients of the message?''), there is a convenience function mu4e-message-contact-field-matches to make this easy.

  * The message body is only available in the message view, not in the headers view.

Note that in headers-mode, you only have access to a reduced message plist, without the information about the message-body or mime-parts; mu4e does this for performance reasons. And even in view-mode, you do not have access to arbitrary message-headers.

However, it is possible to get the information indirectly, using the raw-message and some third-party tool like procmail's formail:

     (defun my-mu4e-any-message-field-at-point (hdr)
       "Quick & dirty way to get an arbitrary header HDR at
     point. Requires the 'formail' tool from procmail."
       (replace-regexp-in-string "\n$" ""
         (shell-command-to-string
           (concat "formail -x " hdr " -c < "
             (shell-quote-argument (mu4e-message-field-at-point :path))))))

Contact functions
=================

It can sometimes be useful to discard or rewrite the contact information that mu4e provides, for example to fix spelling errors, or omit unwanted contacts.

To handle this, mu4e provides mu4e-contact-process-function, which, if defined, is applied to each contact. If the result is nil, the contact is discarded, otherwise the (modified or not) contact information is used.

Each contact is a full e-mail address as you would see in a contact-field of an e-mail message, e.g.,
"Foo Bar" <foo.bar@example.com>
or
cuux@example.com

An example mu4e-contact-process-function might look like:

     (defun my-contact-processor (contact)
       (cond
         ;; remove unwanted
         ((string-match-p "evilspammer@example.com" contact) nil)
         ((string-match-p "noreply" contact) nil)
         ;;
         ;; jonh smiht --> John Smith
         ((string-match "jonh smiht" contact)
            (replace-regexp-in-string "jonh smiht" "John Smith" contact))
         (t contact)))

     (setq mu4e-contact-process-function 'my-contact-processor)

Utility functions
=================

mu4e-utils contains a number of utility functions; we list a few here. See their docstrings for details:

  * mu4e-read-option: read one option from a list. For example:

          (mu4e-read-option "Choose an animal: "
          '(("Monkey" . monkey) ("Gnu" . gnu) ("xMoose" . moose)))

     The user is presented with:

          Choose an animal: [M]onkey, [G]nu, [x]Moose

  * mu4e-ask-maildir: ask for a maildir; try one of the shortcuts (mu4e-maildir-shortcuts), or the full set of available maildirs.

  * mu4e-running-p: return t if the mu4e process is running, nil otherwise.

  * (mu4e-user-mail-address-p addr): return t if ADDR is one of the user's e-mail addresses (as per (mu4e-personal-addresses)).

  * mu4e-log logs to the mu4e debugging log if it is enabled; see mu4e-toggle-logging.

  * mu4e-message, mu4e-warning, mu4e-error are the mu4e equivalents of the normal elisp message, user-error and error functions.

Integrating mu4e with Emacs facilities
**************************************

In this chapter, we discuss how you can integrate mu4e with Emacs in various ways. Here we focus on Emacs built-ins; for dealing with external tools, see Other tools.

Default email client
====================

Emacs allows you to select an e-mail program as the default program it uses when you press C-x m (compose-mail), call report-emacs-bug and so on. If you want to use mu4e for this, you can do so by adding the following to your configuration:

     (setq mail-user-agent 'mu4e-user-agent)

Similarly, to specify mu4e as your preferred method for reading mail, customize the variable read-mail-command.

     (set-variable 'read-mail-command 'mu4e)

(see Emacs (Mail Methods))

Modeline
========

One of the most visible ways in which mu4e integrates with Emacs is through the modeline see Mode Line (emacs). The mu4e support for that is handled through a minor-mode mu4e-modeline-mode, which is enabled by default when mu4e is running.

To completely turn off the modeline support, set mu4e-support-modeline to nil before starting mu4e.

mu4e shares information on the modeline in two ways:

  * buffer-specific: information about the search parameters and the current context

  * global: information about unread messages

The buffer-specific items should be fairly self-explanatory - they show, respectively, your search parameters and the current context.

Since mu4e is a query-based email-client, there a lot of flexibilty in what you want to consider ``interesting new mail'', that is the, the query we want to monitor for changes.

The global modeline contains the results of some specific ``favorite'' bookmark query from mu4e-bookmarks. By default, the first one in chosen, but you may want change that by using the :favorite property for a particular query, e.g., as part of MU4E-BOOKMARKS:

      ;; Monitor the inbox folder in the modeline
      (:query "maildir:/inbox" :name "Inbox" :key ?i :favorite t)

The results of this query (the last time it was updated) is shows as some character or emoji (depending on MU4E-USE-FANCY-CHARS) and 2 or 3 numbers, just like what we saw in see Bookmarks and Maildirs, e.g.,

      N:10(+5)/15

this means there are 10 unread messages, with 5 new messages since the baseline, and in total 15 messages.

You can also customize the icon; see MU4E-MODELINE-ALL-CLEAR, MU4E-MODELINE-ALL-READ, MU4E-MODELINE-UNREAD-ITEMS and MU4E-MODELINE-NEW-ITEMS.

Due to the way queries work, the modeline is not immediately updated when you read messages; but going back to the main view (with M-x mu4e restores things.

Desktop notifications
=====================

Depending on your desktop environment, it is possible to get notification when there is new mail.

The default implementation (which you can override) depends on the same system used for the see Bookmarks and Maildirs, in the main view and the see Modeline, and thus gives updates when there new messages compared to some ``baseline'', as discussed earlier.

For now, notifications are implemented for desktop environments that support DBus-based notifications, as per Emacs' notification sub-system see Desktop Notifications (GNU Emacs Lisp Reference Manual).

You can enable mu4e's desktop notifications (provided that you are on a supported system) by setting mu4e-notification-support to t. If you want tweak the details, have a look at mu4e-notification-filter and mu4e-notification-function.

Emacs bookmarks
===============

Note, emacs bookmarks are not to be confused with mu4e's bookmarks; the former are a generic linking system, while the latter are remember stored queries.

mu4e supports linking to the message-at-point through the normal Emacs built-in bookmark system. The links are based on the message's message-id, and thus the bookmarks stay valid even if you move the message around.

Org-mode links
==============

It can be useful to include links to e-mail messages or search queries in your org-mode files. mu4e supports this by default, unless you set mu4e-support-org to nil.

You can use the normal org-mode mechanisms to store links: M-x org-store-link stores a link to a particular message when you are in Message view. When you are in Headers view, M-x org-store-link links to the query if mu4e-org-link-query-in-headers-mode is non-nil, and to the particular message otherwise (which is the default). You can customize the link description using mu4e-org-link-desc-func.

You can insert this link later with M-x org-insert-link. From org-mode, you can go to the query or message the link points to with either M-x org-agenda-open-link in agenda buffers, or M-x org-open-at-point elsewhere --- both typically bound to C-c C-o.

You can also directly capture such links --- for example, to add e-mail messages to your todo-list. For that, mu4e-org has a function mu4e-org-store-and-capture. This captures the message-at-point (or header --- see the discussion on mu4e-org-link-query-in-headers-mode above), then calls org-mode's capture functionality.

You can add some specific capture-template for this. In your capture templates, the following mu4e-specific values are available:

item                                                 | description
-----------------------------------------------------+------------------------
%:date, %:date-timestamp, %d:date-timestamp-inactive | date, org timestamps
%:from, %:fromname, %:fromaddress                    | sender, name/address
%:to, %:toname, %:toaddress                          | recipient, name/address
%:maildir                                            | maildir for the message
%:message-id                                         | message-id
%:path                                               | file system path
%:subject                                            | message subject

For example, to add a message to your todo-list, and set a deadline for processing it within two days, you could add this to org-capture-templates:

       ("P" "process-soon" entry (file+headline "todo.org" "Todo")
       "* TODO %:fromname: %a %?\nDEADLINE: %(org-insert-time-stamp (org-read-date nil t \"+2d\"))")

If you use the functionality a lot, you may want to define key-bindings for that in headers and view mode:

       (define-key mu4e-headers-mode-map (kbd "C-c c") 'mu4e-org-store-and-capture)
       (define-key mu4e-view-mode-map    (kbd "C-c c") 'mu4e-org-store-and-capture)

iCalendar
=========

When Gnus' article-mode is chosen (Message view), it is possible to view and reply to iCalendar events. To enable this feature, add

     (require 'mu4e-icalendar)
     (mu4e-icalendar-setup)

to your configuration. If you want that the original invitation message be automatically trashed after sending the message created by clicking on the buttons “Accept”, “Tentative”, or “Decline”, also add:

     (setq mu4e-icalendar-trash-after-reply t)

When you reply to an iCal event, a line may be automatically added to the diary file of your choice. You can specify that file with

     (setq mu4e-icalendar-diary-file "/path/to/your/diary")

Note that, if the specified file is not your main diary file, add #include "/path/to/your/diary" to you main diary file to display the events.

To enable optional iCalendar→Org sync functionality, add the following:

     (setq gnus-icalendar-org-capture-file "~/org/notes.org")
     (setq gnus-icalendar-org-capture-headline '("Calendar"))
     (gnus-icalendar-org-setup)

Both the capture file and the headline(s) inside it must already exist.

By default, gnus-icalendar-org-setup adds a temporary capture template to the variable org-capture-templates, with the description ``used by gnus-icalendar-org'', and the shortcut key ``#''. If you want to use your own template, create it using the same key and description. This will prevent the temporary one from being installed next time you gnus-icalendar-org-setup is called.

The full default capture template is:

     ("#" "used by gnus-icalendar-org" entry
        (file+olp ,gnus-icalendar-org-capture-file
                  ,gnus-icalendar-org-capture-headline)
        "%i" :immediate-finish t)

where the values of the variables gnus-icalendar-org-capture-file and gnus-icalendar-org-capture-headline are inserted via macro expansion.

If, for example, you wanted to store ical events in a date tree, prompting for the date, you could use the following:

     ("#" "used by gnus-icalendar-org" entry
        (file+olp+datetree path-to-capture-file)
        "%i" :immediate-finish t :time-prompt t)

Note that the default behaviour for datetree targets in this situation is to store the event at the date that you capture it, not at the date that it is scheduled. That's why I've suggested using the :timeprompt t argument. This gives you an opportunity to set the time to the correct value yourself.

You can extract the event time directly, and have the org-capture functions use that to set the datetree location:

     (defun my-catch-event-time (orig-fun &rest args)
       "Set org-overriding-default-time to the start time of the capture event"
       (let ((org-overriding-default-time (date-to-time
                                           (gnus-icalendar-event:start (car args)))))
         (apply orig-fun args)))

     (advice-add 'gnus-icalendar:org-event-save :around #'my-catch-event-time)

If you do this, you'll want to omit the :timeprompt t setting from your capture template.

Speedbar
========

speedbar is an Emacs-extension that shows navigational information for an Emacs buffer in a separate frame. Using mu4e-speedbar, mu4e lists your bookmarks and maildir folders and allows for one-click access to them.

To enable this, add (require 'mu4e-speedbar) to your configuration; then, all you need to do to activate it is M-x speedbar. Then, when then switching to the Main view, the speedbar-frame is updated with your bookmarks and maildirs.

For speed reasons, the list of maildirs is determined when mu4e starts; if the list of maildirs changes while mu4e is running, you need to restart mu4e to have those changes reflected in the speedbar and in other places that use this list, such as auto-completion when jumping to a maildir.

Dired
=====

It is possible to attach files to mu4e messages using dired (emacs), using the following steps (based on a post on the mu-discuss mailing list by Stephen Eglen).

     (add-hook 'dired-mode-hook 'turn-on-gnus-dired-mode)

Then, mark the file(s) in dired you would like to attach and press C-c RET C-a, and you'll be asked whether to attach them to an existing message, or create a new one.

Other tools
***********

In this chapter, we discuss some ways in which mu4e can cooperate with other tools.

Org-contacts
============

Note, mu4e supports built-in address autocompletion; Address autocompletion, and that is the recommended way to do this. However, it is also possible to manage your addresses with org-mode, using org-contacts (https://julien.danjou.info/projects/emacs-packages#org-contacts).

mu4e-actions defines a useful action (Actions) for adding a contact based on the From:-address in the message at point. To enable this, add to your configuration something like:

       (setq mu4e-org-contacts-file  <full-path-to-your-org-contacts-file>)
       (add-to-list 'mu4e-headers-actions
         '("org-contact-add" . mu4e-action-add-org-contact) t)
       (add-to-list 'mu4e-view-actions
         '("org-contact-add" . mu4e-action-add-org-contact) t)

After this, you should be able to add contacts using a o in the headers view and the message view, using the org-capture mechanism. Note, the shortcut character o is due to the first character of org-contact-add.

BBDB
====

Note, mu4e supports built-in address autocompletion; Address autocompletion, and that is the recommended way to do this. However, it is also possible to manage your addresses with the current (2015-06-23) development release of BBDB, or releases of BBDB after 3.1.2. (https://savannah.nongnu.org/projects/bbdb/).

To enable BBDB, add to your ~/.emacs (or its moral equivalent, such as ~/.emacs.d/init.el) the following after the (require 'mu4e) line:

       ;; Load BBDB (Method 1)
       (require 'bbdb-loaddefs)
       ;; OR (Method 2)
       ;; (require 'bbdb-loaddefs "/path/to/bbdb/lisp/bbdb-loaddefs.el")
       ;; OR (Method 3)
       ;; (autoload 'bbdb-insinuate-mu4e "bbdb-mu4e")
       ;; (bbdb-initialize 'message 'mu4e)

       (setq bbdb-mail-user-agent 'mu4e-user-agent)
       (setq mu4e-view-rendered-hook 'bbdb-mua-auto-update)
       (setq mu4e-compose-complete-addresses nil)
       (setq bbdb-mua-pop-up t)
       (setq bbdb-mua-pop-up-window-size 5)
       (setq mu4e-view-show-addresses t)

After this, you should be able to:

  * In mu4e-view mode, add the sender of the email to BBDB with C-u :

  * Tab-complete addresses from BBDB when composing emails

  * View the BBDB contact while viewing a message

Sauron
======

The Emacs package sauron (Sauron can be found at https://github.com/djcb/sauron, or in the MELPA (Milkypostman’s Emacs Lisp Package Archive) package repository at https://melpa.org/) (by the same author) can be used to get notifications about new mails. If you run something like the below script from your crontab (or have some other way of having it execute every n minutes), you receive notifications in the sauron-buffer when new messages arrive.

#!/bin/sh

# the mu binary
MU=mu

# put the path to your Inbox folder here
CHECKDIR="/home/$LOGNAME/Maildir/Inbox"

sauron_msg () {
DBUS_COOKIE="/home/$LOGNAME/.sauron-dbus"
if test "x$DBUS_SESSION_BUS_ADDRESS" = "x"; then
  if test -e $DBUS_COOKIE; then
    export DBUS_SESSION_BUS_ADDRESS="`cat $DBUS_COOKIE`"
  fi
fi
if test -n "x$DBUS_SESSION_BUS_ADDRESS"; then
  dbus-send --session                          \
    --dest="org.gnu.Emacs"                     \
    --type=method_call                         \
      "/org/gnu/Emacs/Sauron"                  \
      "org.gnu.Emacs.Sauron.AddMsgEvent"       \
      string:shell uint32:3 string:"$1"
fi
}

#
# -mmin -5: consider only messages that were created / changed in the
# the last 5 minutes
#
for f in `find $CHECKDIR -mmin -5 -a -type f -not -iname '.uidvalidity'`; do
  subject=`$MU view $f | grep '^Subject:' | sed 's/^Subject://'`
  sauron_msg "mail: $subject"
done

You might want to put:

     (setq sauron-dbus-cookie t)

in your setup, to allow the script to find the D-Bus session bus, even when running outside its session.

Hydra
=====

People sometimes ask about having multi-character shortcuts for bookmarks; an easy way to achieve this, is by using an emacs package called Hydra (https://github.com/abo-abo/hydra).

With Hydra installed, we can add multi-character shortcuts, for instance:

     (defhydra my-mu4e-bookmarks-work (:color blue)
       "work bookmarks"
       ("b" (mu4e-search "banana AND maildir:/work") "banana")
       ("u" (mu4e-search "flag:unread AND maildir:/work")   "unread"))

     (defhydra my-mu4e-bookmarks-personal (:color blue)
       "personal bookmarks"
       ("c" (mu4e-search "capybara AND maildir:/personal") "capybara")
       ("u" (mu4e-search "flag:unread AND maildir:/personal")  "unread"))

     (defhydra my-mu4e-bookmarks (:color blue)
       "mu4e bookmarks"
       ("p" (my-mu4e-bookmarks-personal/body) "Personal")
       ("w" (my-mu4e-bookmarks-work/body) "Work"))

     Now, you can bind a convenient key to my-mu4e-bookmarks/body.

Example configurations
**********************

In this chapter, we show some example configurations. While it is very useful to see some working settings, we'd like to warn against blindly copying such things.

Minimal configuration
=====================

An (almost) minimal configuration for mu4e might look like this --- as you see, most of it is commented-out.

     ;; example configuration for mu4e

     ;; make sure mu4e is in your load-path
     (require 'mu4e)

     ;; use mu4e for e-mail in emacs
     (setq mail-user-agent 'mu4e-user-agent)

     ;; these must start with a "/", and must exist
     ;; (i.e.. /home/user/Maildir/sent must exist)
     ;; you use e.g. 'mu mkdir' to make the Maildirs if they don't
     ;; already exist

     ;; below are the defaults; if they do not exist yet, mu4e offers to
     ;; create them. they can also functions; see their docstrings.
     ;; (setq mu4e-sent-folder   "/sent")
     ;; (setq mu4e-drafts-folder "/drafts")
     ;; (setq mu4e-trash-folder  "/trash")

     ;; smtp mail setting; these are the same that `gnus' uses.
     (setq
        message-send-mail-function   'smtpmail-send-it
        smtpmail-default-smtp-server "smtp.example.com"
        smtpmail-smtp-server         "smtp.example.com"
        smtpmail-local-domain        "example.com")

Longer configuration
====================

A somewhat longer configuration, showing some more things that you can customize.

     ;; example configuration for mu4e
     (require 'mu4e)

     ;; use mu4e for e-mail in emacs
     (setq mail-user-agent 'mu4e-user-agent)

     ;; the next are relative to the root maildir
     ;; (see `mu info`).
     ;; instead of strings, they can be functions too, see
     ;; their docstring or the chapter 'Dynamic folders'
     (setq mu4e-sent-folder   "/sent"
           mu4e-drafts-folder "/drafts"
           mu4e-trash-folder  "/trash")

     ;; the maildirs you use frequently; access them with 'j' ('jump')
     (setq mu4e-maildir-shortcuts
         '((:maildir "/archive" :key ?a)
           (:maildir "/inbox"   :key ?i)
           (:maildir "/work"    :key ?w)
           (:maildir "/sent"    :key ?s)))

     ;; the headers to show in the headers list -- a pair of a field
     ;; and its width, with `nil' meaning 'unlimited'
     ;; (better only use that for the last field.
     ;; These are the defaults:
     (setq mu4e-headers-fields
         '( (:date          .  25)    ;; alternatively, use :human-date
            (:flags         .   6)
            (:from          .  22)
            (:subject       .  nil))) ;; alternatively, use :thread-subject

     (add-to-list 'mu4e-bookmarks
         ;; ':favorite t' i.e, use this one for the modeline
        '(:query "maildir:/inbox" :name "Inbox" :key ?i :favorite t))

     ;; program to get mail; alternatives are 'fetchmail', 'getmail'
     ;; isync or your own shellscript. called when 'U' is pressed in
     ;; main view.

     ;; If you get your mail without an explicit command,
     ;; use "true" for the command (this is the default)
     (setq mu4e-get-mail-command "offlineimap")

     ;; general emacs mail settings; used when composing e-mail
     ;; the non-mu4e-* stuff is inherited from emacs/message-mode
     (setq mu4e-compose-reply-to-address "foo@bar.example.com"
           user-mail-address "foo@bar.example.com"
           user-full-name  "Foo X. Bar")
     (setq mu4e-compose-signature
        "Foo X. Bar\nhttp://www.example.com\n")

     ;; smtp mail setting
     (setq
        message-send-mail-function 'smtpmail-send-it
        smtpmail-default-smtp-server "smtp.example.com"
        smtpmail-smtp-server "smtp.example.com"
        smtpmail-local-domain "example.com"

        ;; if you need offline mode, set these -- and create the queue dir
        ;; with 'mu mkdir', i.e.. mu mkdir /home/user/Maildir/queue
        smtpmail-queue-mail  nil
        smtpmail-queue-dir  "/home/user/Maildir/queue/cur")

     ;; don't keep message buffers around
     (setq message-kill-buffer-on-exit t)

Gmail configuration
===================

Gmail is a popular e-mail provider; let's see how we can make it work with mu4e. Since we are using IMAP, you must enable that in the Gmail web interface (in the settings, under the ``Forwarding and POP/IMAP''-tab).

Gmail users may also be interested in Including related messages, and in Skipping duplicates.

Setting up offlineimap
----------------------

First of all, we need a program to get the e-mail from Gmail to our local machine; for this we use offlineimap; on Debian (and derivatives like Ubuntu), this is as easy as:

$ sudo apt-get install offlineimap

while on Fedora (and similar) you need:
$ sudo yum install offlineimap

Then, we can configure offlineimap by editing ~/.offlineimaprc:

[general]
accounts = Gmail
maxsyncaccounts = 3

[Account Gmail]
localrepository = Local
remoterepository = Remote

[Repository Local]
type = Maildir
localfolders = ~/Maildir

[Repository Remote]
type = IMAP
remotehost = imap.gmail.com
remoteuser = USERNAME@gmail.com
remotepass = PASSWORD
ssl = yes
maxconnections = 1

Obviously, you need to replace USERNAME and PASSWORD with your actual Gmail username and password. After this, you should be able to download your mail:

$ offlineimap
 OfflineIMAP 6.3.4
Copyright 2002-2011 John Goerzen & contributors.
Licensed under the GNU GPL v2+ (v2 or any later version).

Account sync Gmail:
 ***** Processing account Gmail
 Copying folder structure from IMAP to Maildir
 Establishing connection to imap.gmail.com:993.
Folder sync [Gmail]:
 Syncing INBOX: IMAP -> Maildir
 Syncing [Gmail]/All Mail: IMAP -> Maildir
 Syncing [Gmail]/Drafts: IMAP -> Maildir
 Syncing [Gmail]/Sent Mail: IMAP -> Maildir
 Syncing [Gmail]/Spam: IMAP -> Maildir
 Syncing [Gmail]/Starred: IMAP -> Maildir
 Syncing [Gmail]/Trash: IMAP -> Maildir
Account sync Gmail:
 ***** Finished processing account Gmail

We can now run mu to make sure things work:

$ mu index
mu: indexing messages under /home/foo/Maildir [/home/foo/.cache/mu/xapian]
| processing mail; checked: 520; updated/new: 520, cleaned-up: 0
mu: elapsed: 3 second(s), ~ 173 msg/s
mu: cleaning up messages [/home/foo/.cache/mu/xapian]
/ processing mail; checked: 520; updated/new: 0, cleaned-up: 0
mu: elapsed: 0 second(s)

We can run both the offlineimap and the mu index from within mu4e, but running it from the command line makes it a bit easier to troubleshoot as we are setting things up.

Note: when using encryption, you probably do not want to synchronize your Drafts-folder, since it contains the unencrypted messages. You can use OfflineIMAP's folderfilter for that.

Settings
--------

Next step: let's make a mu4e configuration for this:

     (require 'mu4e)

     ;; use mu4e for e-mail in emacs
     (setq mail-user-agent 'mu4e-user-agent)

     (setq mu4e-drafts-folder "/[Gmail].Drafts")
     (setq mu4e-sent-folder   "/[Gmail].Sent Mail")
     (setq mu4e-trash-folder  "/[Gmail].Trash")

     ;; don't save message to Sent Messages, Gmail/IMAP takes care of this
     (setq mu4e-sent-messages-behavior 'delete)

     ;; (See the documentation for `mu4e-sent-messages-behavior' if you have
     ;; additional non-Gmail addresses and want assign them different
     ;; behavior.)

     ;; setup some handy shortcuts
     ;; you can quickly switch to your Inbox -- press ``ji''
     ;; then, when you want archive some messages, move them to
     ;; the 'All Mail' folder by pressing ``ma''.

     (setq mu4e-maildir-shortcuts
         '( (:maildir "/INBOX"              :key ?i)
            (:maildir "/[Gmail].Sent Mail"  :key ?s)
            (:maildir "/[Gmail].Trash"      :key ?t)
            (:maildir "/[Gmail].All Mail"   :key ?a)))

     (add-to-list 'mu4e-bookmarks
         ;; ':favorite t' i.e, use this one for the modeline
        '(:query "maildir:/inbox" :name "Inbox" :key ?i :favorite t))

     ;; allow for updating mail using 'U' in the main view:
     (setq mu4e-get-mail-command "offlineimap")

     ;; something about ourselves
     (setq
        user-mail-address "USERNAME@gmail.com"
        user-full-name  "Foo X. Bar"
        mu4e-compose-signature
         (concat
           "Foo X. Bar\n"
           "http://www.example.com\n"))

     ;; sending mail -- replace USERNAME with your gmail username
     ;; also, make sure the gnutls command line utils are installed
     ;; package 'gnutls-bin' in Debian/Ubuntu

     (require 'smtpmail)
     (setq message-send-mail-function 'smtpmail-send-it
        starttls-use-gnutls t
        smtpmail-starttls-credentials '(("smtp.gmail.com" 587 nil nil))
        smtpmail-auth-credentials
          '(("smtp.gmail.com" 587 "USERNAME@gmail.com" nil))
        smtpmail-default-smtp-server "smtp.gmail.com"
        smtpmail-smtp-server "smtp.gmail.com"
        smtpmail-smtp-service 587)

     ;; alternatively, for emacs-24 you can use:
     ;;(setq message-send-mail-function 'smtpmail-send-it
     ;;     smtpmail-stream-type 'starttls
     ;;     smtpmail-default-smtp-server "smtp.gmail.com"
     ;;     smtpmail-smtp-server "smtp.gmail.com"
     ;;     smtpmail-smtp-service 587)

     ;; don't keep message buffers around
     (setq message-kill-buffer-on-exit t)

And that's it --- put the above in your ~/.emacs, change USERNAME etc. to your own, and restart Emacs, and run M-x mu4e.

Other settings
==============

Finally, here are some more settings that are useful, but not enabled by default for various reasons.

     ;; use 'fancy' non-ascii characters in various places in mu4e
     (setq mu4e-use-fancy-chars t)

     ;; save attachment to my desktop (this can also be a function)
     (setq mu4e-attachment-dir "~/Desktop")

     ;; attempt to show images when viewing messages
     (setq mu4e-view-show-images t)

FAQ --- Frequently Asked Questions
**********************************

In this chapter we list a number of actual and anticipated questions and their answers.

General
=======

Results from mu and mu4e differ - why?
--------------------------------------

 In general, the same queries for mu and mu4e should yield the same results. If they differ, this is usually because one of the following reasons:

  * different options: mu4e defaults to having mu4e-headers-include-related, and mu4e-headers-results-limit set to 500. However, the command-line mu find's corresponding --include-related is false, and there's no limit (--maxnum).

  * reverse sorting: The results may be different when mu4e and mu find do not both sort their results in the same direction.

  * shell quoting issues: Depending on the shell, various shell metacharacters in search query (such as *) may be expanded by the shell before mu ever sees them, and the query may not be what you think it is. Quoting is necessary.

The unread/all counts in the main-screen differ from the 'real' numbers - what's going on?
------------------------------------------------------------------------------------------

For speed reasons, the counts do not exclude messages that no longer exist in the file-system, nor does it exclude duplicate messages; see mu-mu4e-differ.

How can I quickly delete/move/trash a lot of messages?
------------------------------------------------------

You can select ('mark' in Emacs-speak) the messages like you would select text in a buffer; the actions you then take (e.g., DEL for delete, m for move and t for trash) apply to all selected messages. You can also use functions like mu4e-headers-mark-thread (T), mu4e-headers-mark-subthread (t) to mark whole threads at the same time, and mu4e-headers-mark-pattern (%) to mark all messages matching a certain regular expression.

Can I automatically apply the marks on messages when leaving the headers buffer?
--------------------------------------------------------------------------------

Yes you can --- see the documentation for the variable mu4e-headers-leave-behavior.

How can I set mu4e as the default e-mail client in Emacs?
---------------------------------------------------------

See Default email client.

Can mu4e use some fancy Unicode instead of these boring plain-ASCII ones?
-------------------------------------------------------------------------

Glad you asked! Yes, if you set mu4e-use-fancy-chars to t, mu4e uses such fancy characters in a number of places. Since not all fonts include all characters, you may want to install the unifont and/or symbola fonts on your system.

Can I start mu4e in the background?
-----------------------------------

Yes --- if you provide a prefix-argument (C-u), mu4e starts, but does not show the main-window.

Does mu4e support searching for CJK (Chinese-Japanese-Korean) characters?
-------------------------------------------------------------------------

Yes, if you have Xapian 1.2.8 or newer, and set the environment variable XAPIAN_CJK_NGRAM to non-empty before indexing, both when using mu from the command-line and from mu4e.

How can I customize the function to select a folder?
----------------------------------------------------

The mu4e-completing-read-function variable can be customized to select a folder in any way. The variable can be set to a function that receives five arguments, following completing-read. The default value is ido-completing-read; to use emacs's default behavior, set the variable to completing-read. Helm users can use the same value, and by enabling helm-mode use helm-style completion.

With a lot of Maildir folders, jumping to them can get slow. What can I do?
---------------------------------------------------------------------------

Set mu4e-cache-maildir-list to t (make sure to read its docstring).

How can I hide certain messages from the search results?
--------------------------------------------------------

See the variables mu4e-headers-hide-predicate and mu4e-headers-hide-enabled. The latter can be toggled through mu4e-headers-toggle-property.

For example, to filter out GMail's spam folder, set it to:

     (setq mu4e-headers-hide-predicate
          (lambda (msg)
            (string-suffix-p "Spam" (mu4e-message-field msg :maildir))))

I'm getting an error 'Variable binding depth exceeds max-specpdl-size' when using mu4e -- what can I do about it?
-----------------------------------------------------------------------------------------------------------------

The error occurs because mu4e is binding more variables than emacs allows for, by default. You can avoid this by setting a higher value, e.g. by adding the following to your configuration:

     (setq max-specpdl-size 5000)

Retrieving mail
===============

How can I get notifications when receiving mail?
------------------------------------------------

There is mu4e-index-updated-hook, which gets triggered when the indexing process triggered sees an update (not just new mail though). To use this hook, put something like the following in your setup (assuming you have aplay and some soundfile, change as needed):

     (add-hook 'mu4e-index-updated-hook
       (defun new-mail-sound ()
         (shell-command "aplay ~/Sounds/boing.wav&")))

Getting mail through a local mailserver. What should I use for mu4e-get-mail-command?
-------------------------------------------------------------------------------------

Use the literal string "true" (or don't do anything, it's the default) which then uses /bin/true (a command that does nothing and always succeeds). This makes getting mail a no-op, but the messages are still re-indexed.

How can I re-index my messages without getting new mail?
--------------------------------------------------------

Use M-x mu4e-update-index

When I try to run mu index while mu4e is running I get errors
-------------------------------------------------------------

For instance:
mu: mu_store_new_writable: xapian error
  'Unable to get write lock on ~/.cache/mu/xapian: already locked
What to do about this? You get this error because the underlying Xapian database is locked by some other process; it can be opened only once in read-write mode. There is not much mu4e can do about this, but if is another mu instance that is holding the lock, you can ask it to (gracefully) terminate:
   pkill -2 -u $UID mu # send SIGINT
   sleep 1
   mu index
mu4e automatically restarts mu when it needs it. In practice, this seems to work quite well.

How can I disable the Indexing... messages?
-------------------------------------------

Set the variable mu4e-hide-index-messages to non-nil.

IMAP-synchronization and file-name changes
------------------------------------------

Some IMAP-synchronization programs such as mbsync (but not offlineimap) don't like it when message files do not change their names when they are moved to different folders. mu4e can attempt to help with this - you can set the variable mu4e-change-filenames-when-moving to non-nil.

offlineimap and UTF-7
---------------------

offlineimap uses IMAP's UTF-7 for encoding non-ascii folder names, while mu expects UTF-8 (so, e.g. /まりもえお (some Japanese characters) becomes /&MH4wijCCMEgwSg-).

This is best solved by telling offlineimap to use UTF-8 instead --- see https://github.com/djcb/mu/issues/68#issuecomment-8598652.

mbsync or offlineimap do not sync properly
------------------------------------------

Unfortunately, mbsync and/or offlineimap do not always agree with mu about the meaning of various Maildir-flags. If you encounter unexpected behavior, it is recommended you check before and after a sync-operation. If the problem only shows up after sync'ing, the problem is with the sync-program, and it's most productive to complain there.

Also, you may want to ensure that mu4e-index-lazy-check is kept at its default (nil) value, since it seems mbsync can make changes that escape a 'lazy' check.

Furthermore, there have been quite a few related queries on the mailing-list; worthwhile to check out.

Reading messages
================

Opening messages is slower than expected - why?
-----------------------------------------------

mu4e is designed to be very fast, even with large amounts of mail. However, if you experience slowdowns, here are some things to consider:

  * opening messages while indexing: mu4e corresponds with the mu server synchronously; this means that you can do only one thing at a time. The one operation that potentially does take a bit of time is indexing of mail. Since the 1.7.x series you don't have to wait for the indexing to complete, but it can be still be a bit slower because mu is very busy at that time.

     For some strategies to reduce that time, see the next question.

  * getting contact information can take some time: especially when opening mu4e the first time and you have a lot of contacts, it can take a few seconds to process those. Note that mu4e 1.3 and higher only get changed contacts in subsequent updates (after and indexing operation), so this should be less of a concern. And you can tweak what contacts you get using MU4E-COMPOSE-COMPLETE-ONLY-PERSONAL, MU4E-COMPOSE-COMPLETE-ONLY-AFTER and MU4E-COMPOSE-COMPLETE-MAX.

  * decryption / sign verification: encrypted / signed messages sometimes require network access, and this may take a while; certainly if the needed servers cannot be found. Part of this may be that influential environment variables are not set in the emacs environment.

If you still experience unexpected slowness, you can of course file a ticket, but please be sure to mention the following:

  * are all messages slow or only some messages?

  * if it's only some messages, is there something specific about them?

  * in addition, please a (sufficiently censored version of) a message that is slow

  * is opening always slow or only sometimes? When?

How can I word-wrap long lines in when viewing a message?
---------------------------------------------------------

You can toggle between wrapped and non-wrapped states using w. If you want to do this automatically, invoke visual-line-mode in your mu4e-view-rendered-hook (mu4e-view-mode-hook fires too early).

How can I perform custom actions on messages and attachments?
-------------------------------------------------------------

See Actions.

How can I prevent mu4e from automatically marking messages as `read' when I read them?
--------------------------------------------------------------------------------------

Set mu4e-view-auto-mark-as-read to nil.

Does mu4e support including all related messages in a thread, like Gmail does?
------------------------------------------------------------------------------

Yes --- see Including related messages.

There seems to be a lot of duplicate messages --- how can I get rid of them?
----------------------------------------------------------------------------

See Skipping duplicates.

Some messages are almost unreadable in emacs --- can I view them in an external web browser?
--------------------------------------------------------------------------------------------

Indeed, airlines often send messages that heavily depend on html and are hard to digest inside emacs. Fortunately, there's an action (Message view actions) defined for this. Simply add to your configuration:

     (add-to-list 'mu4e-view-actions
       '("ViewInBrowser" . mu4e-action-view-in-browser) t)

Now, when viewing such a difficult message, type aV, and the message opens inside a web browser. You can influence the browser to use with browse-url-generic-program.

How can I read encrypted messages that I sent?
----------------------------------------------

Since you do not own the recipient's key you typically cannot read those mails --- so the trick is to encrypt outgoing mails with your key, too. This can be automated by adding the following snippet to your configuration (courtesy of user kpachnis):

     (require 'epg-config)
     (setq mml2015-use 'epg
           epg-user-id "gpg_key_id"
           mml2015-encrypt-to-self t
           mml2015-sign-with-sender t)

Can I `bounce' or `resend' messages?
------------------------------------

Somewhat --- it is possible to edit a (copy of) an existing message and then send it, using M-x mu4e-compose-resend. This gives you a raw copy of the message, including all headers, encoded parts and so on. Reason for this is that for resending, it is important not to change anything (except perhaps for the To: address when bouncing); since we cannot losslessly decode an existing message, you get the raw version.

Writing messages
================

What's the deal with replies to messages I wrote myself?
--------------------------------------------------------

Like many other mail-clients, mu4e treats replies to messages you wrote yourself as special --- these messages keep the same To: and Cc: as the original message. This is to ease the common case of following up to a message you wrote earlier.

How can I automatically set the From:-address for a reply-message?
------------------------------------------------------------------

See Compose hooks.

How can I dynamically determine the folders for draft/sent/trashed messages?
----------------------------------------------------------------------------

See Dynamic folders.

How can I define aliases for (groups of) e-mail addresses?
----------------------------------------------------------

See (emacs) Mail Aliases.

How can I automatically add some header to an outgoing message?
---------------------------------------------------------------

See Compose hooks.

How can I influence the way the original message looks when replying/forwarding?
--------------------------------------------------------------------------------

Since mu4e-compose-mode derives from message-mode, you can re-use many of its facilities.

How can I easily include attachments in the messages I write?
-------------------------------------------------------------

You can drag-and-drop from your desktop; alternatively, you can use dired --- see Dired.

mu4e seems to remove myself from the Cc:-list; how can I prevent that?
----------------------------------------------------------------------

Set mu4e-compose-keep-self-cc to t in your configuration.

mu4e include myself from the Cc:-list; how can I prevent that?
--------------------------------------------------------------

You need list your personal addresses by passing one or more --my-address=... to mu init. Note that the mu4e-user-mail-address-list which was used in older mu4e versions is no longer used. Also see the entries for version 1.4 in NEWS.org (N) in the main-menu.

How can I start a new message-thread from a reply?
--------------------------------------------------

Remove the In-Reply-To header, and mu4e automatically removes the (hidden) References header as well when sending it. This makes the message show up as a top-level message rather than as a response.

How can I attach an existing message?
-------------------------------------

Use mu4e-action-capture-message (i.e., a c in the headers view) to `capture' the to-be-attached message, then when editing the message, use M-x mu4e-compose-attach-captured-message.

How can I sign or encrypt messages?
-----------------------------------

You can do so using Emacs' MIME-support --- check the Attachments-menu while composing a message. Also see Signing and encrypting.

You can do so using Emacs' MIME-support --- check the Attachments-menu while composing a message. Also see Signing and encrypting.

Address auto-completion does not work?
--------------------------------------

If you have set mu4e-compose-complete-only-personal to non-nil, mu4e only completes 'personal' addresses - so you tell it about your e-mail addresses when setting up the database (mu init); Initializing the message store.

If you cannot find specific addresses you'd expect to find, inspect the values of MU4E-COMPOSE-COMPLETE-ONLY-PERSONAL, MU4E-COMPOSE-COMPLETE-ONLY-AFTER and MU4E-COMPOSE-COMPLETE-MAX.

Can I use BBDB with mu4e?
-------------------------

Yes, with releases of BBDB after 3.1.2. BBDB.

How can I get rid of the message buffer after sending?
------------------------------------------------------

     (setq message-kill-buffer-on-exit t)

Sending big messages is slow and blocks emacs --- what can I do about it?
-------------------------------------------------------------------------

For this, there's https://github.com/jwiegley/emacs-async (also available from the Emacs package repository); add the following snippet to your configuration:

     (require 'smtpmail-async)
     (setq
       send-mail-function 'async-smtpmail-send-it
       message-send-mail-function 'async-smtpmail-send-it)

With this, messages are sent using a background Emacs instance.

A word of warning though, this tends to not be as reliable as sending the message in the normal, synchronous fashion, and people have reported silent failures, where mail sending fails for some reason without any indication of that.

You can check the progress of the background by checking the *Messages*-buffer, which should show something like:
Delivering message to "William Shakespeare" <will@example.com>...
Mark set
Saving file /home/djcb/Maildir/sent/cur/20130706-044350-darklady:2,S...
Wrote /home/djcb/Maildir/sent/cur/20130706-044350-darklady:2,S
Sending...done
The first and final messages are the most important, and there may be considerable time between them, depending on the size of the message.

Is it possible to view headers and messages, or compose new ones, in a separate frame?
--------------------------------------------------------------------------------------

Yes. There is builtin support for composing messages in a new frame. Set the variable mu4e-compose-in-new-frame to t.

However, if you want to personalize the display of all of mu4e's buffers, you can do so by customizing display-buffer-alist.

How can I apply format=flowed to my outgoing messages?
------------------------------------------------------

This enables receiving clients that support this feature to reflow paragraphs. Plain text emails with Content-Type: text/plain; format=flowed can be reflowed (i.e. line endings removed, paragraphs refilled) by receiving clients that support this standard. Clients that don't support this, show them as is, which means this feature is truly non-invasive.

Here's an explanatory blog post which also shows why this is a desirable feature: https://mathiasbynens.be/notes/gmail-plain-text (if you don't have it, your mails mostly look quite bad especially on mobile devices) and here's the RFC with all the details: https://www.ietf.org/rfc/rfc2646.txt.

Since version 0.9.17, mu4e sends emails with format=flowed by setting

     (setq mu4e-compose-format-flowed t)

in your Emacs init file (~/.emacs or ~/.emacs.d/init.el). The transformation of your message into the proper format is done at the time of sending. For this to happen properly, you should write each paragraph of your message of as a long line (i.e. without carriage return). If you introduce unwanted newlines in your paragraph, use M-q to reformat it as a single line.

If you want to send the message with paragraphs on single lines but without format=flowed (because, say, the receiver does not understand the latter as it is the case for Google or Github), use M-x use-hard-newlines (to turn use-hard-newlines off) or uncheck the box format=flowed in the Text menu when composing a message.

How can I force images to be shown at the end of my messages, regardless of where I insert them?
------------------------------------------------------------------------------------------------

User Marcin Borkowski has a solution:

     (defun mml-attach-file--go-to-eob (orig-fun &rest args)
       "Go to the end of buffer before attaching files."
       (save-excursion
         (save-restriction
           (widen)
           (goto-char (point-max))
           (apply orig-fun args))))

     (advice-add 'mml-attach-file :around #'mml-attach-file--go-to-eob)

How can I avoid Outlook display issues?
---------------------------------------

Limited testing shows that certain Outlook clients do not work well with inline replies, and the entire message including-and-below the first quoted section is collapsed. This means recipients may not even notice important inline text, especially if there is some top-posted content. This has been observed on OS X, Windows, and Web-based Outlook clients accessing Office 365.

It appears the bug is triggered by the standard reply regex "On ... wrote:". Changing "On", or removing the trailing ":" appears to fix the bug (in limited testing). Therefore, a simple work-around is to set `message-citation-line-format` to something slightly non-standard, such as:

     (setq  message-citation-line-format "On %Y-%m-%d at %R %Z, %f wrote...")

Known issues
============

Although they are not really questions, we end this chapter with a list of known issues and/or missing features in mu4e. Thus, users won't have to search in vain for things that are not there (yet), and the author can use it as a todo-list.

UTF-8 language environment is required
--------------------------------------

mu4e does not work well if the Emacs language environment is not UTF-8; so, if you encounter problems with encodings, be sure to have (set-language-environment "UTF-8") in your ~/.emacs (or its moral equivalents in other places).

Thread handling is incomplete
-----------------------------

While threads are calculated and are visible in the headers buffer, you cannot collapse/open them.

Key-bindings are somewhat hard-coded.
-------------------------------------

That is, the main menu assumes the default key-bindings, as do the clicks-on-bookmarks.

For a more complete list, please refer to the issues-list in the github-repository.

Tips and Tricks
***************

Fancy characters
================

When using `fancy characters' (mu4e-use-fancy-chars) with the Inconsolata-font (and likely others as well), the display may be slightly off; the reason for this issue is that Inconsolata does not contain the glyphs for the `fancy' arrows and the glyphs that are used as replacements are too high.

To fix this, you can use something like the following workaround (in your .emacs-file):

     (when (equal window-system 'x)
           (set-fontset-font "fontset-default" 'unicode "Dejavu Sans Mono")
           (set-face-font 'default "Inconsolata-10"))

Other fonts with good support for Unicode are unifont and symbola.

For a more complete solution, but with greater overhead, you can also try the unicode-fonts package:

     (require 'unicode-fonts)
     (require 'persistent-soft) ; To cache the fonts and reduce load time
     (unicode-fonts-setup)

It's possible to customize various header marks as well, with a ``fancy'' and ``non-fancy'' version (if you cannot see some the ``fancy'' characters, that is an indication that the font you are using does not support those characters.

      (setq
        mu4e-headers-draft-mark     '("D" . "💈")
        mu4e-headers-flagged-mark   '("F" . "📍")
        mu4e-headers-new-mark       '("N" . "🔥")
        mu4e-headers-passed-mark    '("P" . "❯")
        mu4e-headers-replied-mark   '("R" . "❮")
        mu4e-headers-seen-mark      '("S" . "☑")
        mu4e-headers-trashed-mark   '("T" . "💀")
        mu4e-headers-attach-mark    '("a" . "📎")
        mu4e-headers-encrypted-mark '("x" . "🔒")
        mu4e-headers-signed-mark    '("s" . "🔑")
        mu4e-headers-unread-mark    '("u" . "⎕")
        mu4e-headers-list-mark      '("s" . "🔈")
        mu4e-headers-personal-mark  '("p" . "👨")
        mu4e-headers-calendar-mark  '("c" . "📅"))

Refiling messages
=================

By setting mu4e-refile-folder to a function, you can dynamically determine where messages are to be refiled. If you want to do this based on the subject of a message, you can use a function that matches the subject against a list of regexes in the following way. First, set up a variable my-mu4e-subject-alist containing regexes plus associated mail folders:

     (defvar my-mu4e-subject-alist '(("kolloqui\\(um\\|a\\)" . "/Kolloquium")
                                     ("Calls" . "/Calls")
                                     ("Lehr" . "/Lehre")
                                     ("webseite\\|homepage\\|website" . "/Webseite"))
       "List of subjects and their respective refile folders.")

Now you can use the following function to automatically refile messages based on their subject line:

     (defun my-mu4e-refile-folder-function (msg)
       "Set the refile folder for MSG."
       (let ((subject (mu4e-message-field msg :subject))
             (folder (or (cdar (member* subject my-mu4e-subject-alist
                                        :test #'(lambda (x y)
                                                  (string-match (car y) x))))
                         "/General")))
         folder))

Note the "/General" folder: it is the default folder in case the subject does not match any of the regexes in my-mu4e-subject-alist.

In order to make this work, you'll of course need to set mu4e-refile-folder to this function:

     (setq mu4e-refile-folder 'my-mu4e-refile-folder-function)

If you have multiple accounts, you can accommodate them as well:

     (defun my-mu4e-refile-folder-function (msg)
       "Set the refile folder for MSG."
       (let ((maildir (mu4e-message-field msg :maildir))
             (subject (mu4e-message-field msg :subject))
             folder)
         (cond
          ((string-match "Account1" maildir)
           (setq folder (or (catch 'found
                              (dolist (mailing-list my-mu4e-mailing-lists)
                                (if (mu4e-message-contact-field-matches
                                  msg :to (car mailing-list))
                                    (throw 'found (cdr mailing-list)))))
                            "/Account1/General")))
          ((string-match "Gmail" maildir)
           (setq folder "/Gmail/All Mail"))
          ((string-match "Account2" maildir)
           (setq folder (or (cdar (member* subject my-mu4e-subject-alist
                                           :test #'(lambda (x y)
                                                     (string-match
                                                        (car y) x))))
                            "/Account2/General"))))
         folder))

This function actually uses different methods to determine the refile folder, depending on the account: for Account2, it uses my-mu4e-subject-alist, for the Gmail account it simply uses the folder ``All Mail''. For Account1, it uses another method: it files the message based on the mailing list to which it was sent. This requires another variable:

     (defvar my-mu4e-mailing-lists
       '(("mu-discuss@googlegroups.com" . "/Account1/mu4e")
         ("pandoc-discuss@googlegroups.com" . "/Account1/Pandoc")
         ("auctex@gnu.org" . "/Account1/AUCTeX"))
       "List of mailing list addresses and folders where
        their messages are saved.")

Saving outgoing messages
========================

Like mu4e-refile-folder, the variable mu4e-sent-folder can also be set to a function, in order to dynamically determine the save folder. One might, for example, wish to automatically put messages going to mailing lists into the trash (because you'll receive them back from the list anyway). If you have set up the variable my-mu4e-mailing-lists as mentioned, you can use the following function to determine a 'sent'-folder:

     (defun my-mu4e-sent-folder-function (msg)
       "Set the sent folder for the current message."
       (let ((from-address (message-field-value "From"))
             (to-address (message-field-value "To")))
         (cond
          ((string-match "my.address@account1.example.com" from-address)
           (if (member* to-address my-mu4e-mailing-lists
                        :test #'(lambda (x y)
                                  (string-match (car y) x)))
               "/Trash"
             "/Account1/Sent"))
          ((string-match "my.address@gmail.com" from-address)
           "/Gmail/Sent Mail")
          (t (mu4e-ask-maildir-check-exists "Save message to maildir: ")))))

Note that this function doesn't use (mu4e-message-field msg :maildir) to determine which account the message is being sent from. The reason is that the function in mu4e-sent-folder is called when you send the message, but before mu4e has created the message struct from the compose buffer, so that mu4e-message-field cannot be used. Instead, the function uses message-field-value, which extracts the values of the headers in the compose buffer. This means that it is not possible to extract the account name from the message's maildir, so instead the from address is used to determine the account.

Again, the function shows three different possibilities: for the first account (my.address@account1.example.com) it uses my-mu4e-mailing-lists again to determine if the message goes to a mailing list. If so, the message is put in the trash folder, if not, it is saved in /Account1/Sent. For the second (Gmail) account, sent mail is simply saved in the Sent Mail folder.

If the from address is not associated with Account1 or with the Gmail account, the function uses mu4e-ask-maildir-check-exists to ask the user for a maildir to save the message in.

Confirmation before sending
===========================

To protect yourself from sending messages too hastily, you can add a final confirmation, which you can of course make as elaborate as you wish.

     (add-hook 'message-send-hook
       (lambda ()
         (unless (yes-or-no-p "Sure you want to send this?")
           (signal 'quit nil))))

Another option is to simply set message-confirm-send to non-nil so the question ``Send message?'' is asked for confirmation.

How it works
************

While perhaps not interesting for all users of mu4e, some curious souls may want to know how mu4e does its job.

High-level overview
===================

At a high level, we can summarize the structure of the mu4e system using some ascii-art:

                   +---------+
                   | emacs   |
                   |    +------+
                   +----| mu4e | --> send mail (smtpmail)
                        +------+
                         |  A
                         V  |  ---/ search, view, move mail
                   +---------+    \
                   |   mu    |
                   +---------+
                     |    A
                     V    |
                   +---------+
                   | Maildir |  <--- receive mail (fetchmail,
                   +---------+                     offlineimap, ...)

In words:

  * Your e-mail messages are stored in a Maildir-directory (typically, ~/Maildir and its subdirectories), and new mail comes in using tools like fetchmail, offlineimap, or through a local mail server.

  * mu indexes these messages periodically, so you can quickly search for them. mu can run in a special server-mode, where it provides services to client software.

  * mu4e, which runs inside Emacs is such a client; it communicates with mu (in its server-mode) to search for messages, and manipulate them.

  * mu4e uses the facilities offered by Emacs (the Gnus message editor and smtpmail) to send messages.

mu server
=========

mu4e is based on the mu e-mail searching/indexer. The latter is a C++-program; there are different ways to communicate with a client that is emacs-based.

One way to implement this, would be to call the mu command-line tool with some parameters and then parse the output. In fact, that was the first approach --- mu4e would invoke e.g., mu find and process the output in Emacs.

However, with this approach, we need to load the entire e-mail Xapian database (in which the message is stored) for each invocation. Wouldn't it be nicer to keep a running mu instance around? Indeed, it would --- and thus, the mu server sub-command was born. Running mu server starts a simple shell, in which you can give commands to mu, which then spits out the results/errors. mu server is not meant for humans, but it can be used manually, which is great for debugging.

Reading from the server
=======================

In the design, the next question was what format mu should use for its output for mu4e (Emacs) to process. Some other programs use JSON here, but it seemed easier (and possibly, more efficient) just to talk to Emacs in its native language: s-expressions, and interpret those using the Emacs-function read-from-string. See The message s-expression for details on the format.

So, now let's look at how we process the data from mu server in Emacs. We'll leave out a lot of details, mu4e-specifics, and look at a bit more generic approach.

The first thing to do is to create a process (for example, with start-process), and then register a filter function for it, which is invoked whenever the process has some data for us. Something like:

       (let ((proc (start-process <arguments>)))
         (set-process-filter proc 'my-process-filter)
         (set-process-sentinel proc 'my-process-sentinel))

Note, the process sentinel is invoked when the process is terminated --- so there you can clean things up. The function my-process-filter is a user-defined function that takes the process and the chunk of output as arguments; in mu4e it looks something like (pseudo-lisp):

     (defun my-process-filter (proc str)
       ;; mu4e-buf: a global string variable to which data gets appended
       ;; as we receive it
       (setq mu4e-buf (concat mu4e-buf str))
       (when <we-have-received-a-full-expression>
           <eat-expression-from mu4e-buf>
           <evaluate-expression>))

<evaluate-expression> de-multiplexes the s-expression we got. For example, if the s-expression looks like an e-mail message header, it is processed by the header-handling function, which appends it to the header list. If the s-expression looks like an error message, it is reported to the user. And so on.

The language between frontend and backend is documented partly in the mu-server man-page and more completely in the output of mu server --commands.

mu4e can log these communications; you can use M-x mu4e-toggle-logging to turn logging on and off, and you can view the log using M-x mu4e-show-log ($).

The message s-expression
========================

As a word of warning, the details of the s-expression are internal to the mu4e - mu communications, and are subject to change between versions.

A typical message s-expression looks something like the following:

     (:docid 32461
      :from ((:name "Nikola Tesla" :email "niko@example.com"))
      :to ((:name "Thomas Edison" :email "tom@example.com"))
      :cc ((:name "Rupert The Monkey" :email "rupert@example.com"))
      :subject "RE: what about the 50K?"
      :date (20369 17624 0)
      :size 4337
      :message-id "C8233AB82D81EE81AF0114E4E74@123213.mail.example.com"
      :path  "/home/tom/Maildir/INBOX/cur/133443243973_1.10027.atlas:2,S"
      :maildir "/INBOX"
      :priority normal
      :flags (seen attach)
      ....
     ")

This s-expression forms a property list (plist), and we can get values from it using plist-get; for example (plist-get msg :subject) would get you the message subject. However, it's better to use the function mu4e-message-field to shield you from some of the implementation details that are subject to change; and see the other convenience functions in mu4e-message.el.

Some notes on the format:

  * The address fields are lists of plists of the form (:name <name>   :email <email>), where name can be nil.

  * The date is in format Emacs uses (for example in current-time). (Emacs 32-bit integers have only 29 bits available for the actual number; the other bits are use by Emacs for internal purposes. Therefore, we need to split time_t in two numbers.)

Example: ping-pong
------------------

As an example of the communication between mu4e and mu, let's look at the ping-pong-sequence. When mu4e starts, it sends a command ping to the mu server backend, to learn about its version. mu server then responds with a pong s-expression to provide this information (this is implemented in mu-cmd-server.c).

We start this sequence when mu4e is invoked (when the program is started). It calls mu4e--server-ping, and registers a (lambda) function for mu4e-server-pong-func, to handle the response.

-> (ping)
<-<prefix>(:pong "mu" :props (:version "x.x.x" :doccount 78545))

When we receive such a pong (in mu4e-server.el), the lambda function we registered is called, and it compares the version we got from the pong with the version we expected, and raises an error if they differ.

Debugging
*********

As explained in How it works, mu4e communicates with its backend (mu server) by sending commands and receiving responses (s-expressions).

For debugging purposes, it can be very useful to see this data. For this reason, mu4e can log all these messages. Note that the `protocol' is documented to some extent in the mu-server manpage.

You can enable (and disable) logging with M-x mu4e-toggle-logging. The log-buffer is called *mu4e-log*, and in the Main view, Headers view and Message view, there's a keybinding $ that takes you there. You can quit it by pressing q.

Logging can be a bit resource-intensive, so you may not want to leave it on all the time. By default, the log only maintains the most recent 1200 lines. mu itself keeps a log as well, you can find it in <MUHOME>/mu.log, on Unix typically ~/.cache/mu/mu.log.

GNU Free Documentation License
******************************

     [file fdl.texi not included]