Mutt – A Command Line Email Client to Send Mails from Terminal
As a System admin, sometimes we need to send mails to users or someone else from the server and for that we used to go with a web based interface to send email, is it really that handy ? Absolutely No.

Here in this tutorial, we’ll be using the mutt (a terminal email client) command to send email from command line interlace.
What is Mutt?
Mutt is a command line based Email client. It’s a very useful and powerful tool to send and read mails from command line in Unix based systems. Mutt also supports POP and IMAP protocols for receiving mails. It opens with a coloured interface to send Email which makes it user friendly to send emails from command line.
Mutt Features
Some other important features of Mutt is as follows:
- Its very Easy to install and configure.
- Allows us to send emails with attachments from the command line.
- It also has the features to add BCC (Blind carbon copy) and CC (Carbon copy) while sending mails.
- It allows message threading.
- It provides us the facility of mailing lists.
- It also support so many mailbox formats like maildir, mbox, MH and MMDF.
- Supports at least 20 languages.
- It also support DSN (Delivery Status Notification).
How to Install Mutt in Linux
We can install Mutt Client in our Linux box very easily with any package installers as shown.
Configuration files
Configuration files of Mutt Email client.
- Main Configuration file: To make changes globally for all users For mutt, you can make changes in its mail configuration file “/etc/Muttrc“.
- User Configuration file of Mutt : If you want to set some specific configuration for a particular user for Mutt, you can configure those settings in
Basic Syntax of mutt command
Read Emails with Mutt
To read emails of the user with you are currently logged in, you just need to run “mutt” on the terminal, it will load the current user’s mailbox.

To read the emails of a specific user, you need to specify which mail file to read. For example, You (as root) wants to read mails of user “John“, you need to specify his mail file with “-f” option with mutt command.
You may also use “-R” option to open a mailbox in read-only mode.
Send an email with mutt command
In this example, following command will send a test Email to [email protected]. The “-s” option is used to specify Subject of the mail.
When you enter the above command in the terminal, it opens up with an interface and confirms the recipient address and subject of the mail and opens up the interface, here you can make changes to recipient mail address.
- Change recipient email address pressing t.
- Change Cc address with c.
- Attach files as attachments with a.
- Quit from the interface with q.
- Send that email by pressing y.
Note: When you press “y” it shows the status below that mutt is sending mail.

Add Carbon copy(Cc) and Blind Carbon copy(Bcc)
We can add Cc and Bcc with mutt command to our email with “-c” and “-b” option.
Here in this example, root is sending email to [email protected] and putting [email protected] as Cc address and [email protected] as Bcc.

Send Emails with Attachments
We can send email from command line with attachments by using “-a” option with mutt command.

Here in above snapshot, you can see that it shows attachment attached with the mail.
Use of muttrc file
If we want to change the senders name and email, then we need to Create a file in that particular user’s home directory.
Add the following lines to it. Save and close it.
Getting Help
To print the help menu of “mutt”, we need to specify “-h” option with it.
This is it with mutt command for now, read man pages of mutt for more information on mutt command.
Tutorial Feedback.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Mail/Mutt
Mutt — мощный консольный клиент почты. Он может практически все, что и другие почтовики с графикой, но отличается меньшим потреблением ресурсов компьютера, и, так как является консольным, с успехом работает через фреймбуфер. Это позволяет использовать его на машинах без Х-сервера, со слабыми видеокартами или по сети, экономя трафик и позволяя игнорировать слабость канала.
Содержание
Настройка
mutt использует как опции командной строки, так и конфигурационные файлы. Опции используются для отладки, однако чаще применяются в пакетном режиме для создания автоматических писем:
Здесь -s — тема письма; -b — адрес для скрытой копии; -c — адрес для копии; -a — вложение в письмо; — — конец списка опций; admin@firma.domain — основной адрес; команда echo по конвейеру | передает тело письма. Естественно, в реальных ситуациях вместо большинства параметров используются переменные, подставляющие адресатов, меняющие тему и текст под нужную ситуацию.
Для настройки mutt требуется править файлы в
/.mutt . Ранее все настройки находились в одном файле .muttrc, теперь для каждого вида настроек (alias, set, bind, folder и т.д.) есть свои файлы. Однако файл muttrc остался, теперь в нем находятся не принадлежащие к прочим категориям настройки. (Если вы импортируете готовые настройки, скопируйте файл .muttrc вместо текущего, а после правки к своим предпочтениям разнесите по разделам.)
Здесь приведены краткие сведения, более подробно следует смотреть man muttrc (на рус.), /usr/share/doc/mutt*/index.html (на англ.), официальная wiki (на англ.).
alias
Используется вместо адресной книги, для каждого адресата или списка рассылки можно создать свой псевдоним, при вводе которого в поле To: при создании письма, в поле адресата автоматически подставится реальное имя и адрес. Формат:
alias псевдоним «реальное имя» <адрес>
Создать псевдоним можно из самого mutt , нажав во время чтения письма a (появится внизу экрана).
Первые две строки переназначают клавиши в встроенном просмотрщике; следующие три устанавливают клавишу x для выхода из меню подстановки псевдонимов, просмотра вложений, выбора вложений. Формат:
bind карта ключ функция. Примеры параметров в /usr/share/doc/mutt*/configuration.html#bind .
charset
Полезно для приема почты от разных отступающих от стандарта почтовиков, которые указывают кодировку в произвольном формате. Формат: charset-hook псевдоним_ака_неправильное_название правильная_кодировка
color
Устанавливает цветовую гамму для просмотра и прочих действий с письмами. Первая строка — цвет вложений; вторая и третья — цвет определенных заголовков; последняя — цвет подписи. Формат:
color привязка цвет_переднего_плана цвет_фона [регулярное выражение]
folder
Устанавливает настройки для папок с почтой. Первая указывает папку на компьютере, где хранятся почтовые папки (строго говоря, это не папки, а файлы, которые содержат письма в определенном формате); вторая определяет локальные папки, которые надо отслеживать на предмет новой почты; третья предписывает при входе в папку mailru устанавливать отправителем stalker999@mail.ru. Формат третьей команды:
folder-hook [!] регулярное_выражение_имя _папки команда [; команда]
Устанавливает настройки шифрования/подписывания писем. Формат — см set
header
Описывает операции с заголовками писем. Первая строка описывает порядок следования заголовков при чтении/написании письма. Вторая и третья указывают показывать только определенные и скрывать все остальные. Четвертая определяет формат для своего заголовка, например, сообщает некоторую информацию о используемой программе либо добавляет другой адрес в поле Reply-to:. Формат нагляден.
muttrc
Содержит все команды, не относящиеся ни к какой из прочих категорий. Так как этот файл единственный, который читает программа при запуске, содержит директиву source, загружающую остальные файлы. Пример:
source
Основная команда, изменяющая подавляющее большинство настроек. Устанавливаемые значения (в зависимости от опции):
- string — строка (если есть пробелы, заключается в кавычки)
- boolean — yes/no (включено/выключено), есть состояние «не установлена»
- quadoption — предыдущая с добавочными значениями «предлагать да/предлагать нет» (yes/no значения применяются сразу, при установке ask-yes/ask-no предлагается подтвердить умолчание/изменить параметр для этого раза)
- number — целое положительное число.
Первая строка устанавливает таймаут проверки новых сообщений в почтовой папке (не на сервере); вторая указывает не удалять почту на POP-сервере при получении в локальный ящик; третья предписывает при таймауте POP-сессии не соединяться заново,а ожидать подтверждения от пользователя, предлагая по умолчанию вариант «да»; четвертая устанавливает ящик, который будет показываться при запуске программы (знак = в начале названия означает локальный ящик в локальной папке); пятая — устанавливает редактором писем внешнюю программу vi с передачей ей некоторых параметров. Формат:
set параметр=значение
Использование
mutt имеет низкий порог вхождения, основные команды могут показываться в строке подсказки, кроме того, из любого места (кроме внешнего редактора, конечно) можно комбинацией клавиш ? вызвать контекстную справку по доступным для данного места командам. Управление осуществляется только клавиатурой, английской раскладкой, заглавные и строчные буквы отличаются, поддерживаются комбинации вида «нажать Esc, отпустить, нажать m» — замена Meta-клавиши, уже не присутствующей на современных клавиатурах, а также макросы — последовательность из команд, запускаемых одной/несколькими последовательно нажатыми клавишами. Команды, которые могут потребоваться новичкам:
- Enter — прочитать сообщение либо подтвердить команду;
- Tab — следующее новое сообщение, при отсутствии — следующее непрочитанное;
- L (Shift+l) — ответить в список рассылки;
- ^D (Control+d) — удалить ВСЮ просматриваемую дискуссию;
- ^U (Control+u) — отменить удаление (так как на сообщение, помеченное к удалению, mutt не переходит, «перепрыгивает» его, следует перейти к ближайшему вышестоящему и серией нажатий u или ^U восстановить нужное);
- % (Shift+5) — запретить/разрешить изменения почтового ящика (может быть полезно, если вы отметили к удалению не те письма, которые хотели, и не можете восстановить статус-кво);
- m — создать новое сообщение;
- c — перейти в папку (подставляется имя папки с новой почтой, если есть);
- r — ответить отправителю подсвеченного/читаемого письма;
- d — удалить подсвеченное/читаемое письмо;
- u — восстановить удаленное (смотри примечание к ^U);
- G — получить новую почту;
- q — выход
Дополнительная функциональность
Все же mutt нельзя считать самодостаточной почтовой программой, некоторая функциональность в нем отсутствует, другая ограничена. Благодаря тому, что его создатели придерживаются общепринятых стандартов, возможно расширить его возможности путем подключения сторонних программ. В таблице приведены некоторые доппрограммы, которые можно подключить к mutt :
Установка mutt в Unix/Linux

Mutt — клиент командной строки для работы с электронной почтой. Это очень полезный и мощный инструмент для отправки и чтения писем из командной строки в системах Unix и Linux. Данная утилита также поддерживает POP и IMAP протоколы для получения почты.
В этой статье «Установка mutt в Unix/Linux» я расскажу о утилите mutt (терминал клиента для электронной почты) и как ею пользоваться чтобы отправить письмо из командной строки.
Особенности mutt.
Некоторые важные особенности mutt заключается в следующем:
- Его очень легко установить и настроить.
- Позволяет посылать электронные письма с вложениями файлами прямо из командной строки.
- Она также имеет свои особенности по добавлению BCC (скрытой копии) и CC (Carbon Copy — копия) при отправке почты.
- Он дает нам возможность отправлять письма сразу на много ящиков ( выполнять массовую рассылку).
- Он также поддерживает множество форматов (Maildir, Mbox, MH и MMDF).
- Имеется поддержка по крайней мере на 20 языках.
- Он также поддерживает DSN (статус уведомления о доставке).
Установка mutt в Unix/Linux
Чтобы установить mutt клиент на машину необходимо выполнить команду, как показано ниже.
Установка mutt на Debian/Ubuntu
Чтобы выполнить установку, используйте:
Установка mutt на RHEL/CentOS/Fedora
Чтобы установить mutt клиент на машину необходимо выполнить команду, как показано ниже:
Установка mutt на другие Unix/Linux
Для остальных ОС, можно собрать из исходного кода:
Смотрим помощь по «configure»:
Так что это команда для конфигурирования:
Исправление ( т.к я пример привожу на CentOS):
И потом, собственно, устанавливаем:
Проверьте размер созданного бинарного файла:
Получаем, 2.5мб — Это много! Выполняем еще кое-что:
И проверяем снова:
А теперь, он весит — 749K.
Можно посмотреть версию так:
Чтобы выполнить установку на Mac OS X:
И потом, выполняем поиск пакета:
Видим, что он имеется и можно его установить:
Конфигурация утилиты mutt для отправки писем в Unix/Linux
Можно настроить данный клиент под себя, основной конфигурационный файл: Чтобы внести изменения для всех пользователей mutt, нужно внести изменения в его конфигурационном файле /etc/muttrc.
Можно настроить данный клиент под себя, конфигурационный файл для пользователя: Если вы хотите установить некоторые настройки для конкретного пользователя Mutt, вы можете настроить эти параметры в
Использование файла muttrc.
Если вы хотим изменить имя и адрес электронной почты отправителей, то вы должны создать файл в домашнем каталоге этого пользователя:
И прописать следующее:
Настоящее_имя_пользователя — имя пользователя.
Использование mutt для отправки писем в Unix/Linux.
Базовый синтаксис команды mutt.
Чтение электронных писем с mutt
Чтобы прочитать электронные письма пользователя нужно запустить «mutt» на терминале, она будет загружать почтовый ящик текущего пользователя:
Для чтения электронной почты конкретного пользователя, необходимо указать почтовый файл для чтения. Например, вы (как пользователь root) хочет читать почту пользователя «captain», то вы должны указать его почтовый файл с опцией «-f» в команде mutt:
Вы также можете использовать опцию «-R», чтобы открыть почтовый ящик в режиме только для чтения.
Отправить письмо с помощью команды mutt
В этом примере, следующая команда отправить тестовое e-mail пользователю user@linux-notes.org. Опция «-s» используется для указания текста сообщения:
Когда вы выполните команду в терминале, он откроет интерфейс и нужно подтвердить адрес получателя и тему, здесь вы можете внести изменения:
- Изменить адрес электронной почты получателя, нажатием «t».
- Изменить адрес «Cc», нажатием «c».
- Прикрепить файлы вложения, нажатием «a».
- Выйти из интерфейса можно нажав «q».
- Отправить это письмо, нажав «y».
Примечание: При нажатии «Y» показывает статус что mutt посылает почту.
Добавить Cc и (Bcc) для отправки копий с помощью команды mutt.
Так же, можно добавить Cc и Bcc:
Где, address_recipient — адресс получателя.
Отправка писем с вложенными файлами используя mutt.
Мы можем отправлять электронную почту из командной строки с вложениями:
Где, address_recipient — адресс получателя.
Опции утилиты mutt для отправки писем в Unix/Linux
Для получения помощи.
Чтобы показать список всех команд «mutt», вы должны указать опцию «-h»:
Вот список команд:
-a <path_to_file>- присоединить файл к сообщению
-b <address> — указать скрытый адрес копии (BCC)
-c <address> — указать адрес копии (CC)
-e <command> — указать команду, которая будет выполнена после инициализации
-f <file> — указать почтовый ящик для чтения
-F <file> — указать альтернативный файл muttrc
-H <file> — указать черновик файла для чтения заголовка из файла
-i <file> — указать файл, который Mutt должен включить в ответ
-m <type> — указать тип почтового ящика по умолчанию
-n — заставляет Mutt не читать систему Muttrc
-p — вызвать отложенное сообщение
-R — почтовый ящик в режиме чтения
-s <subj> — указать тему (должен быть в кавычках, если в ней есть пробелы)
-v — показать версию и определения время компиляции
-x — имитировать режим отправки почты mailx
-y — выбрать почтовый ящик, указанный в вашем списке `mailboxes ‘
-z — немедленно выйти, если в почтовом ящике нет сообщений
-Z — открыть первую папку с новым сообщением, немедленно выйти, если ее нет
-h — вызвать помощь
Вот и все, тема «Установка утилиты mutt для отправки писем в Unix/Linux» завершена.
Mutt linux как пользоваться
Mutt is a text-based mail client renowned for its powerful features. Though over two decades old, Mutt remains the mail client of choice for a great number of power users.
Mutt focuses primarily on being a Mail User Agent (MUA), and was originally written to view mail. Later implementations (added for retrieval, sending, and filtering mail) are simplistic compared to other mail applications and, as such, users may wish to use external applications to extend Mutt’s capabilities.
Nevertheless, the Arch Linux mutt package is compiled with IMAP, POP3 and SMTP support, removing the necessity for external applications.
This article covers using both native IMAP sending and retrieval, and a setup depending on OfflineIMAP or getmail (POP3) to retrieve mail, procmail to filter it in the case of POP3, and msmtp to send it.
Installation
Install the mutt package. Alternatively consider using the #NeoMutt package.
Optionally install external helper applications for an IMAP setup, such as isync or OfflineIMAP.
- If you just need the methods LOGIN and PLAIN, these are satisfied with the dependency libsasl
- If you want to (or have to) use CRAM-MD5, GSSAPI or DIGEST-MD5, install the package cyrus-sasl-gssapi
- If you are using Gmail as your SMTP server, you may need to install the package cyrus-sasl
NeoMutt
alt=»Tango-go-next.png» width=»48″ height=»48″ />This article or section is a candidate for moving to NeoMutt. alt=»Tango-go-next.png» width=»48″ height=»48″ />
The NeoMutt project aims to bring together all the patches for Mutt. It adds a large set of features. Lots of old Mutt patches have been brought up-to-date, tidied and documented.
While there are many different packages of Mutt in the AUR, each of them providing another set of patches, NeoMutt aims to replace them in the future by implementing appropriate compile options.
NeoMutt can be installed with the neomutt package or alternatively from the AUR at neomutt-git AUR for the development version.
Configuration
This section covers #IMAP, #POP3, #Maildir and #SMTP configuration.
Mutt will, by default, search six locations for its configuration file;
/.mutt/muttrc , and $XDG_CONFIG_HOME/mutt/muttrc , first with -MUTT_VERSION appended, then without. Any of these locations will work. In case you decide to put the initialization file somewhere else, use $ mutt -F /path/to/.muttrc . You should also know some prerequisite for Mutt configuration. Its syntax is very close to the Bourne Shell. For example, you can get the content of another configuration file:
You can use variables and assign the result of shell commands to them.
Here the $ gets escaped so that it does not get substituted by Mutt before being passed to the shell. Also note the use of the backquotes, as bash syntax $(. ) does not work. Mutt has a lot of predefined variables, but you can also set your own. User variables must begin with «my»!
Native IMAP support
The mutt package is compiled with IMAP support. At the very least you need to have four lines in your muttrc file to be able to access your mail.
imap_user
imap_pass
If unset, the password will be prompted for.
folder
Instead of a local directory which contains all your mail (and directories), use your server (and the highest folder in the hierarchy, if needed).
You do not have to use a folder, but it might be convenient if you have all your other folders inside your INBOX, for example. Whatever you set here as your folder can be accessed later in Mutt with just an equal sign (=) or a plus sign (+). Example:
It should be noted that for several accounts, it is best practice to use different folders — e.g. for account-hook. If you have several Gmail accounts, use
instead, where your account is username@gmail.com. This way it will be possible to distinguish the different folders. Otherwise it would lead to authentication errors.
spoolfile
The spoolfile is the folder where your (unfiltered) e-mail arrives. Most e-mail services conventionally name it INBOX. You can now use ‘=’ or ‘+’ as a substitution for the full folder path that was configured above. For example:
mailboxes
Any IMAP folders that should be checked regularly for new mail should be listed here:
Alternatively, check for all subscribed IMAP folders (as if all were added with a mailboxes line):
These two versions are equivalent if you want to subscribe to all folders. So the second method is much more convenient, but the first one gives you more flexibility. Also, newer Mutt versions are configured by default to include a macro bound to the ‘y’ key which will allow you to change to any of the folders listed under mailboxes.
If you do not set this variable, the spoolfile will be used by default. This variable is also important for the #Sidebar.
Summary
Using these options, you will be able to start Mutt, enter your IMAP password, and start reading your mail. Here is a muttrc snippet (for Gmail) with some other lines you might consider adding for better IMAP support.
External IMAP support
While IMAP support is built into Mutt, it does not download mail for offline use. It is possible to use an external application such as OfflineIMAP or isync to download your emails to a local folder which can then be processed by Mutt.
Consider using applications such as spamassassin or imapfilter AUR to sort mail.
The mutt package is compiled with POP3 support, which is configured via the pop_* variables as described in muttrc(5) .
Alternatively, it is possible to use external programs to fetch mail using POP3. One popular option is to use getmail for retrieving and procmail for filtering the mail.
Maildir
Maildir is a generic and standardized format. Almost every MUA is able to handle Maildirs and Mutt’s support is excellent. There are just a few simple things that you need to do to get Mutt to use them. Open your muttrc and add the following lines:
This is a minimal Configuration that enables you to access your Maildir and checks for new local Mails in INBOX. This configuration also caches the headers of the eMails to speed up directory-listings. It might not be enabled in your build (but it sure is in the Arch-Package). Note that this does not affect OfflineIMAP in any way. It always syncs all of the directories on a Server. spoolfile tells Mutt which local directories to poll for new Mail. You might want to add more Spoolfiles (for example the Directories of Mailing-Lists) and maybe other things. But this is subject to the Mutt manual and beyond the scope of this document.
Whether you use POP or IMAP to receive mail you will probably still send mail using SMTP.
Folders
There is basically only one important folder here: the one where all your sent e-mails will be saved.
Gmail automatically saves sent e-mail to +[Gmail]/Sent , so we do not want duplicates.
Native SMTP support
The mutt package is compiled with SMTP support.
Note that if your SMTP credentials are the same as your IMAP credentials, then you can use those variables:
You may need to tweak the security parameters. If you get an error like SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol , then your server probably uses the SMTP instead of SMTPS.
There are other variables that you may need to set. For example for use of STARTTLS:
If your server uses the LOGIN authentication method you might need to specify this explicitly, despite the manual’s claim that all methods are tried by default:
See muttrc(5) for more information.
External SMTP support
An external SMTP agent such as msmtp, sSMTP or opensmtpd can also be used.
The sendmail variable in your muttrc determines the program and arguments used to deliver mail in mutt. Any additional arguments must be interpreted by the program as recipient addresses.
For example, if using msmtp:
Sending mails from Mutt
Now, startup mutt :
You should see all the mail in
/mail/inbox . Press m to compose mail; it will use the editor defined by your EDITOR environment variable. If this variable is not set, you can fix it before starting Mutt:
You should store the EDITOR value into your shell resource configuration file (such as bashrc). You can also set the editor from Mutt’s configuration file:
For testing purposes, address the letter to yourself. After you have written the letter, save and exit the editor. You will return to Mutt, which will now show information about your e-mail. Press y to send it.
Multiple accounts
Now you should have a working configuration for one account at least. You might wonder how to use several accounts, since we put everything into a single file.
Well all you need is to write account-specific parameters to their respective files and source them. All the IMAP/POP3/SMTP configuration for each account should go to its respective folder.
Mutt can handle this thanks to one of its most powerful features: hooks. Basically a hook is a command that gets executed before a specific action. There are several hooks available. For multiple accounts, you must use account-hooks and folder-hooks.
- Folder-hooks will run a command before switching folders. This is mostly useful to set the appropriate SMTP parameters when you are in a specific folder. For instance when you are in your work mailbox and you send a e-mail, it will automatically use your work account as sender.
- Account-hooks will run a command every time Mutt calls a function related to an account, like IMAP syncing. It does not require you to switch to any folder.
Hooks take two parameters:
The regex is the folder to be matched (or not if preceded by the !). The command tells what to do.
Let us give a full example:
Finally .mutt/personal should be similar to .mutt/work .
Now all your accounts are set, start Mutt. To switch from one account to another, just change the folder ( c key). Alternatively you can use the sidebar.
To change folder for different mailboxes you have to type the complete address — for IMAP/POP3 folders, this may be quite inconvenient — let us bind some key to it.
With the above shortcuts (or with the sidebar) you will find that changing folders (with c by default) is not contextual, i.e. it will not list the folders of the current mailbox, but of the one used the last time you changed folders. To make the behaviour more contextual, the trick is to press = or + for current mailbox. You can automate this with the following macro:
Passwords management
Keep in mind that writing your password in .muttrc is a security risk. One solution is to always enter the password manually, but this becomes cumbersome.
An alternative solution is to encrypt your password with GnuPG in an encrypted file. Setup your own keypair if you have not done so already. Create a file in a tmpfs with the following contents:
Then encrypt this file, setting yourself as the recipient and move it into an accessible location. In this example the encrypted file resides at $HOME/.my-pwds.gpg.
In your mutt configuration file add the following before any account:
This decrypts the file quietly and sets the variable my_pass in this example. This can be used in any variable after it has been sourced. For example:
If you use external tools like OfflineIMAP and msmtp, you need to set up an agent (e.g. gpg-agent, see GnuPG#gpg-agent) to keep the passphrase into cache and thus avoiding those tools always prompting for it.
You can also use pass to encrypt your passwords easily. Just add the passwords to the given passwords as follows:
After that, just add the command pass show user@domain.tld in your muttrc , for instance:
Note the use of both backquotes and regular quotes to prevent the output of the backquotes from being parsed[1].
Security concern
If enter-command is available from the UI, it is possible to see the password unencrypted, which may be undesired if anybody else than you has access to your session while Mutt is running. You may want to disable it for this reason. As a consequence, every command that the user intends to use must be bound to a key in advance, otherwise it will never be accessible.
Tips and tricks
Guides to get you started with using and customizing Mutt:
-
(maintained by Bruno Postle) (maintained by Randall Wood) (by Steve Losh) (by Justin R. Miller)
If you have any Mutt specific questions, feel free to ask in the IRC channel.
Key bindings
The default key bindings are quite far from the more common Emacs-like or Vi-like bindings. You can customize them to your preference. Mutt has a different set of bindings for the pager, the index, the attachment view, etc. Thus you need to specify which map you want to modify when you bind a key. You can review the list of commands and key bindings from Mutt’s help page (default key: ? ). Example of Vi-like bindings:
Composition
Encrypt and sign mail (GnuPG)
To start encrypting mail in mutt using GnuPG copy /usr/share/doc/mutt/samples/gpg.rc to your mutt configuration folder (e.g. to
/.mutt/gpg.rc ). Then append the following to your mutt configuration file (e.g.
Most encryption options are then available by pressing p in the compose view.
See the pgp_* and crypt_* options in muttrc(5) .
E-mail character encoding
When using Mutt there are two levels where the character sets that must be specified:
- The text editor used to write the e-mail must save it in the desired encoding.
- Mutt will then check the e-mail and determine which encoding is the more appropriate according to the priority you specified in the send_charset variable. Default: «us-ascii:iso-8859-1:utf-8».
So if you write an e-mail with characters allowed in ISO-8859-1 (like ‘résumé’), but without characters specific to Unicode, then Mutt will set the encoding to ISO-8859-1.
To avoid this behaviour, set the variable in your muttrc :
The first compatible charset starting from the left will be used. Since UTF-8 is a superset of US-ASCII it does not harm to leave it in front of UTF-8, it may ensure old MUA will not get confused when seeing the charset in the e-mail header.
Custom mail headers
One of the greatest thing in Mutt is that you can have full control over your mail header.
First, make your headers editable when you write e-mails:
Mutt also features a special function my_hdr for customizing your header. Yes, it is named just like a variable, but in fact it is a function.
You can clear it completely, which you should do when switching accounts with different headers, otherwise they will overlap:
Other variables have also an impact on the headers, so it is wise to clear them before using my_hdr :
Now, you can add any field you want — even non-standard one — to your header using the following syntax:
Note that <VALUE> can be the result of a command.
Signature block
Create a .signature in your home directory. Your signature will be appended at the end of your email. Alternatively you can specify a file in your Mutt configuration:
Random signature
You can use fortune (package fortune-mod ) to add a random signature to Mutt.
Create a fortune file and then add the following line to your .muttrc:
Note the pipe at the end. It tells Mutt that the specified string is not a file, but a command.
Compose and send from command line
Man pages will show all available commands and how to use them, but here are a couple of examples. You could use Mutt to send alerts, logs or some other system information, triggered by login through .bash_profile , or as a regular cron job.
Send a message with attachment:
Compose HTML e-mails
Since Mutt has nothing of a WYSIWIG client, HTML is quite straightforward, and you can do much more than with all WYSIWIG mail clients around since you edit the source code directly. Simply write your mail using HTML syntax. For example:
Now before sending the mail, use the edit-type command (default shortcut Ctrl+t ), and replace text/plain by text/html .
Display another email while composing
A common complaint with Mutt is that when composing a new mail (or reply), you cannot open another mail (i.e. for checking with another correspondent) without closing the current mail (postponing). The following describes a solution:
First, fire up Mutt as usual. Then, launch another terminal window. Now start a new Mutt with
This starts Mutt in read-only mode, and you can browse other emails at your convenience. It is strongly recommended to always launch a second Mutt in read-only mode, as conflicts will easily arise otherwise.
Printing
You can install muttprint AUR for fancier printing quality. In your muttrc file, insert:
Viewing content
Viewing URLs in a web browser
Your should start by creating a .mutt directory in $HOME if not done yet. There, create a file named macros. Insert the following:
Then install the urlview AUR package.
Create a .urlview in $HOME and insert the following:
When you read an email on the pager, hitting ctrl+b will list all the urls from the email. Navigate up or down with arrow keys and hit enter on the desired url. Your browser will start and go to the selected site.
Some browser will require additional arguments to work properly. For example, Luakit will close on Mutt exit. You need to fork it to background, using the -n parameter:
The 2>/dev/null is to make it quiet, i.e. to prevent useless message printing where you do not want them to.
Viewing HTML
It is possible to pass the HTML body to an external HTML program and then dump it, keeping email viewing uniform and unobtrusive. Three programs are described here: lynx , w3m and elinks (make sure the selected package is installed).
/.mutt/mailcap does not exist you will need to create it and save the following to it.
or, in case of w3m,
or, in case of elinks,
or, in case of elinks (with color support),
/.muttrc and add the following,
To automatically open HTML messages in lynx, w3m or elinks add this additional line to the muttrc:
The beauty of this is, instead of seeing an HTML body as source or being opened by a separate program, in this case lynx, you see the formatted content directly, and any URL links within the email can be displayed with Ctrl+b , assuming you have urlview AUR installed.
If you receive many emails with multiple or alternate encodings, Mutt may default to treating every email as HTML. To avoid this, add the following variable to your
/.muttrc to have Mutt default to text when available and use w3m/lynx only when no text version is available in the email:
Some HTML mails may not display correctly in a text-based web browser. As a fallback solution, you can bind a key to open a graphical browser in such cases. The following macro will open the HTML mail selected from the attachment view in the web browser defined in the environment. (Feel free to adapt the
If $BROWSER is firefox , then set intl.charset.fallback.utf8_for_file to true in about:config as described in [2] to ensure non-ASCII characters in the HTML page are displayed correctly.
Filtering the message view
You can restrict the view to e-mails matching a pattern and specific properties with the limit command (default shortcut: l ).
To view all e-mails containing «foo» in the header, simply write «foo» and you are done. To remove the filter, use the «all» keyword.
To view all flagged messages, use
To view all unread messages that are either of size ≥1MB or from johndoe, use
All possible patterns are listed in the official manual.
Conversation grouping
The default sort order is by date. Use the sort-mailbox command (default key: o ) to change the sorting option. You can group e-mails by conversation/thread, in which case you can define how to sort threads and how to sort within a thread.
In the following example, threads are sorted according to the date of their last e-mail.
Configuring editors to work with mutt
- To limit the width of text to 72 characters, edit your .vimrc file and add:
- To reformat a modified text see the Vim context help
GNU nano
nano is another nice console editor to use with Mutt.
To limit the width of text to 72 characters, edit your .nanorc file and add:
If you do not want to limit the width of text globally, you can pass the column number as an argument to the hard-wrap option in your muttrc file, e.g.:
Also, in muttrc file, you can specify the line to start editing so that you will skip the mail header:
Emacs
Emacs has a mail and a message major mode. To switch to mail-mode automatically when Emacs is called from Mutt, you can add the following to your .emacs :
If you usually run Emacs daemon, you may want Mutt to connect to it. Add this to your .muttrc :
Display settings
Colors
Append the contents of /usr/share/doc/mutt/samples/colors.linux to your .muttrc file, or copy and source it. Then adjust to your liking.
The actual color each of these settings will produce depends on the colors set in your
Alternatively, you can source any file you want containing colors (and thus act as a theme file). See [3] for a theme example.
Index Format
Here follows a quick example to put in your .muttrc to customize the Index Format, i.e. the columns displayed in the folder view.
Display recipient instead of sender in «Sent» folder view
By default Mutt uses the %L format string in the index_format variable, which will display:
- «To <list-name>», if an address in the «To:» or «Cc:» header field matches an address defined by the user’s subscribe command.
- Otherwise it displays the author name, or recipient name if the message is from you.
If you use multiple email addresses in the same mailbox, make sure to configure the alternates variable, so that Mutt knows which messages were from you.
Variable column width
If you resize the window, the subject might get truncated while there is still unused space left for some fields, like for the sender. You can get the maximum number of columns supported by your terminal (i.e. the width) using a shell call to tput cols . With this value, you can set a percentage of the width to fields like Sender and Subject.
Example using the above folder-hook and a sidebar width of 24:
We must set the variables my_col_from and my_col_from from within the hooks. Otherwise, the column values will not get re-computed.
We can add a binding to force re-computing the index format without changing folder:
Sidebar
Example settings for a sidebar are in /usr/share/doc/mutt/samples/sample.muttrc-sidebar , including keybindings. Copy, edit, and source that file in your mutt configuration file. Be sure to change set sidebar_visible = yes .
Append the following in order to toggle the sidebar visibility:
Note that with the mailboxes option, folders appear in the order they were set to mailboxes if you do not use the sidebar_sort_method option.
Display the index above the pager view
Set the following variable in your muttrc :
Contact management
Address aliases
Aliases is the way Mutt manages contacts. An alias is nickname [longname] <address>.
- The nickname is what you will type in Mutt to get your contact address. One word only, and should be easy to remember.
- The longname is optional. It may be several words.
- An <address> must be in a valid form (i.e. with an @ ).
It is quite simple indeed. Add this to .muttrc :
- alias_file is the file where the information is getting stored when you add an alias from within Mutt.
- sort_alias specifies which field to use to sort the alias list when displayed in Mutt. Possible values: alias, address.
- reverse_alias if set to yes mutt will display the «personal» name from your aliases in the index menu if it finds an alias that matches the message’s sender.
- source $alias_file tells Mutt to read aliases on startup. Needed for auto-completion.
Now all you have to do when prompted To: is writing the alias instead of the full address. The beauty of it is that you can auto-complete the alias using Tab . Autocompleting a wrong or an empty string will display the full list. You can select the alias as usual, or by typing its index number.
There are two ways to create aliases:
- From Mutt, press a when an e-mail of the targetted person if selected.
- Edit the alias_file manually. The syntax is really simple:
Abook
abook AUR is a stand-alone program dedicated to contact management. It uses a very simple text-based interface and contacts are stored in a plain text, human-readable database. Besides the desired contact properties are extensible (birthday, address, fax, and so on).
Abook is specifically designed to be interfaced with Mutt, so that it can serve as a full, more featured replacement of Mutt internal aliases. If you want to use Abook instead of aliases, remove the aliases configuration in .muttrc and add this:
See abook(1) and abookrc(5) for more details and a full configuration sample.
Goobook
Goobook allows you to search your Google contacts from the command line or from within Mutt and can be installed with the goobook AUR or goobook-git AUR packages.
Before using goobook you must configure
/.goobookrc . To generate the default template:
/.goobookrc for configuration options. At a minimum, you will need to enter your email and password.
In order to authenticate with Google, you must generate a Client ID and Client secret. See [4] for details.
If you want to use Goobook instead of aliases, remove any alias configuration in .muttrc and add:
When composing an email message within mutt, Tab will now search your Google contacts. While viewing messages a will add the sender to Google contacts.
Khard
khard is a command-line addressbook that uses locally-stored carddav address book entries. You can use vdirsyncer to sync those with CardDAV servers.
The integration in mutt is similar to abook, see khard documentation.
Manage multiple sender accounts
If you use multiple sender accounts, you can automatically associate a specific sender account with a recipient. mutt-vid AUR scans sent emails for the most recent «From» details associated with specific recipients, saving these in a file for mutt to source. The next time you email this recipient, mutt will automatically invoke a send-hook with the same email address and real name that you used previously. See mutt-vid’s homepage for more details.
Request IMAP mail retrieval manually
If you do not want to wait for the next automatic IMAP fetching (or if you did not enable it), you might want to fetch mails manually. There is a mutt command imap-fetch-mail for that. Alternatively, you could bind it to a key:
Avoiding slow index on large (IMAP) folders due to coloring
Index highlighting by regex is nice, but can lead to slow folder viewing if your regex checks the body of the message.
Use folder-hook for only highlighting in, for example, the inbox (if you manage to empty your mailbox efficiently):
Speed up folders switch
Add this to your .muttrc :
Archive treated e-mails
When you read an e-mail, you have four choices: Answer it, Flag it, Archive it or Delete it. If you have this in mind, you can keep your inbox slim and fit with this macro (set up for Gmail):
Migrating mails from one computer to another
In case you are transfering your mails to a new machine (copy&paste), you probably need to delete the header cache (a file or folder like
/.cache/mutt if you followed the above configuration) to make Mutt able to read your migrated E-Mails. Otherwise Mutt may freeze.
Note that if you had a folder created for you header cache, all mailboxes will have their own cache file, so you can delete caches individually without having to remove everything.
Default folder for saving attachments
By default Mutt will save attachments to the folder it was started from. If you want to always set the default destination to
/attachments , you can create the following alias, which launches Mutt in this folder:
If you are using bash, you can use pushd and popd to restore the directory state after mutt exits.
Pager behavior
Show context lines when going to next page:
Stop at the end instead of displaying next mail:
Fast reply
By default Mutt will ask to confirm the recipient and the subject when you reply to an e-mail. It will also ask if you want to include the original mail in your answer. If you assume you will always stick to the default values, you can set up Mutt to skip these questions:
You can still edit the recipient and the subject before sending.
Ignore own e-mail addresses from group-reply
Mutt will include your e-mail address(es) in the recipient list when you group-reply to a mail you were CC’ed. You can ask Mutt to ignore some addresses with:
IMAP message cache
When using the built-in IMAP support, e-mails are fetched in memory by default. Retrieving a big e-mail several times will download it from your IMAP server that many times.
Alternatively, you can ask Mutt to store all fetched messages on disk:
(The folder must exist.) This will make any future retrieval instantaneous, even with big attachments.
If you want to purge the cache from its oldest e-mails exceeding a limit of, say, 50MB, you can use a script like the following:
and call it on startup:
Open attachments or view HTML email in the background
By default, opening the attachments in the mutt will block mutt. You can edit
/.mutt/mailcap to append an & so mutt will launch one of the Default applications in the backgroud. Take xdg-open as an example,
&> /dev/null is used to prevent any error or message from cluttering the mutt terminal window. And nametemplate=%s.html is used because chromium refuse to render local files without .html extension as HTML.
Troubleshooting
Backspace does not work in Mutt
This is a common problem with some xterm-like terminals. Two solutions:
- Either rebind the key in .muttrc
Note that ^? is one single character representing backspace in caret notation. To type in Emacs, use Ctrl+q Backspace , in Vim Ctrl+v Backspace .
- Or fix your terminal:
Edit termbs.src and change kbs=^H to kbs=\177 , then:
The change-folder function always prompt for the same mailbox
This is not a bug, this is actually an intended behaviour. See the multiple accounts section for a workaround.
I cannot change folder when using Mutt read-only (Mutt -R)
This is certainly because you are using macros like this one:
This macro tells Mutt to sync (which is a write operation) before switching.
Either use the sidebar or set another macro:
Error sending message, child exited 127 (Exec error.).
This is an SMTP error. It means that mutt does not know how to send the message. You can either try installing sendmail and see if that solves your issue, or you can set the smtp_url variable. If you use gmail, you can add the following to your muttrc to tell mutt to use gmails smtp server.
Take note of the smtps protocol, it is important. This should solve the problem.
Character encoding problems
If you are having problems with character encoding, first read this section in the Mutt wiki.
If Chinese text is still garbled, it may help to decode with GBK even when GB2312 is specified in the header. You can do this with iconv by adding the following to your mailcap file:
and enabling it by adding a line to your .muttrc :
For HTML emails, you can edit the relevant line of your mailcap by replacing %
Unable to login with GMail
Gmail disables access from applications it considers less secure, including mutt . You can enable access by following the instructions here
Not possible to open too long URLs with urlview
Too long URLs are not parsed correctly, because urlview does not decode text (see [5]). You can let mutt decode the e-mails instead. Replace the line for opening urlview with the following code:
Another option is to use urlscan instead, which gives a text user interface to select the URL and can deal with much stranger text formats.
Documentation
Newcomers may find it quite hard to find help for Mutt. Actually most of the topics are covered in the official documentation. We urge you to read it.