Mutt (the mutt e-mail client)

Sending E-Mail with Mutt

Note: This is no longer needed since Mutt 1.5.15, which now has its own SMTP system. To make use of this, you must put this in your ~/.muttrc:

# Set smtp url
set smtp_url="smtp://user@domain.org"

If you want SSL encryption put smtps:// instead of smtp:// in the above example.

Remote SMTP server example:

set smtp_url = "smtp://user@smtp.domain:25"  # ESMTP with TLS
set smtp_pass="pass"
set from="user@domain"
set realname="username"

Note: you may need to change record and postponed based on the server. Check nixtricks at wordpress for details.

set record="=INBOX.Sent Messages"
set postponed="=INBOX.Drafts"

3.4 Setting variables based upon mailbox

Usage: pattern command

It is often desirable to change settings based on which mailbox you are
reading. The folder-hook command provides a method by which you can execute
any configuration command. pattern is a regular expression specifying
in which mailboxes to execute command before loading. If a mailbox
matches multiple folder-hook’s, they are executed in the order given in the
muttrc.

Note: if you use the «!» shortcut for
at the beginning of the pattern, you must place it
inside of double or single quotes in order to distinguish it from the
logical not operator for the expression.

However, the sorting method is not restored to its previous value when
reading a different mailbox. To specify a default command, use the
pattern «.»:

3.6 Using color and mono video attributes

Usage: object foreground background
Usage: index foreground background
Usage: index pattern

If your terminal supports color, you can spice up Mutt by creating your own
color scheme. To define the color of an object (type of information), you
must specify both a foreground color and a background color (it is not
possible to only specify one or the other).

object can be one of:

  • attachment
  • body (match regexp in the body of messages)
  • bold (hiliting bold patterns in the body of messages)
  • error (error messages printed by Mutt)
  • header (match regexp in the message header)
  • hdrdefault (default color of the message header in the pager)
  • index (match pattern in the message index)
  • indicator (arrow or bar used to indicate the current item in a menu)
  • markers (the «+» markers at the beginning of wrapped lines in the pager)
  • message (informational messages)
  • normal
  • quoted (text matching
    in the body of a message)
  • quoted1, quoted2, …, quotedN (higher levels of quoting)
  • search (hiliting of words in the pager)
  • signature
  • status (mode lines used to display info about the mailbox or message)
  • tilde (the «~» used to pad blank lines in the pager)
  • tree (thread tree drawn in the message index and attachment menu)
  • underline (hiliting underlined patterns in the body of messages)

foreground and background can be one of the following:

  • white
  • black
  • green
  • magenta
  • blue
  • cyan
  • yellow
  • red
  • default
  • colorx

foreground can optionally be prefixed with the keyword to make
the foreground color boldfaced (e.g., ).

If your terminal supports it, the special keyword default can be
used as a transparent color. The value brightdefault is also valid.
If Mutt is linked against the S-Lang library, you also need to set
the COLORFGBG environment variable to the default colors of your
terminal for this to work; for example (for Bourne-like shells):

Note: The S-Lang library requires you to use the lightgray
and brown keywords instead of white and yellow when
setting this variable.

Note: The uncolor command can be applied to the index object only. It
removes entries from the list. You must specify the same pattern
specified in the color command for it to be removed. The pattern «*» is
a special token which means to clear the color index list of all entries.

Mutt also recognizes the keywords color0, color1, …,
colorN-1 (N being the number of colors supported
by your terminal). This is useful when you remap the colors for your
display (for example by changing the color associated with color2
for your xterm), since color names may then lose their normal meaning.

If your terminal does not support color, it is still possible change the video
attributes through the use of the «mono» command:

Usage: <object> <attribute>

where attribute is one of the following:

  • none
  • bold
  • underline
  • reverse
  • standout

Проброс портов (Port Forwarding)

Необходим для перенаправление сетевых запросов на сервер, стоящий за NAT и не имеющий прямого выхода во внешнюю сеть. Настройки отличаются в зависимости от способа управления брандмауэром netfilter.

Firewalld

firewall-cmd —zone=external —permanent —add-forward-port=port=25:proto=tcp:toport=8025:toaddr=192.168.0.15

* где 25 — прослушиваемый внешний порт, для которого сработает перенаправление; tcp — используемый транспортный протокол; 8025 — на какой порт перенаправить запрос; 192.168.0.15 — IP-адрес сервера, на который отправляем запросы.

Разрешаем сам порт:

firewall-cmd —permanent —zone=external —add-port=25/tcp

Чтобы правило вступило в силу:

firewall-cmd —reload

Iptables

Настройка выполняется двумя командами:

iptables -t nat -A PREROUTING -p tcp -m tcp -d 10.8.232.111 —dport 25 -j DNAT —to-destination 192.168.0.15:8025

iptables -t nat -A POSTROUTING -p tcp -m tcp -s 192.168.0.15 —sport 8025 -j SNAT —to-source 10.8.232.111:25

или можно так:

iptables -t nat -A PREROUTING -p tcp -i eth0 —dport 25 -j DNAT —to-destination 192.168.0.15:8025

iptables -A FORWARD -p tcp -d 192.168.0.15 —dport 8025 -m state —state NEW,ESTABLISHED,RELATED -j ACCEPT

* где eth0 — внешний сетевой интерфейс.

Разрешаем порт:

iptables -I INPUT 1 -p tcp —dport 8025 -j ACCEPT

* обратите внимание, что мы разрешаем порт, на который переводим запрос, так как цепочки POSTROUTING и PREROUTING работают до цепочки FILTER, а потому открывать нужно не входящий порт (25), а тот, на который назначается пакет (8025). Не забываем сохранить правила:

Не забываем сохранить правила:

/usr/libexec/iptables/iptables.init save

или

service iptables save

3.11 User defined headers

Usage:stringfield

The «my_hdr» command allows you to create your own header
fields which will be added to every message you send.

For example, if you would like to add an «Organization:» header field to
all of your outgoing messages, you can put the command

in your .

Note: space characters are not allowed between the keyword and
the colon («:»). The standard for electronic mail (RFC822) says that
space is illegal there, so Mutt enforces the rule.

If you would like to add a header field to a single message, you should
either set the
variable,
or use the edit-headers function (default: «E») in the send-menu so
that you can edit the header of your message along with the body.

To remove user defined header fields, use the «unmy_hdr»
command. You may specify an asterisk («*») to remove all header
fields, or the fields to remove. For example, to remove all «To» and
«Cc» header fields, you could use:

Windows Live

1. Запустите программу Windows Live, в верхнем меню выберите пункт Учетные записи, затем нажмите на кнопку Учетная запись электронной почты.

2. В открывшемся окне укажите:

  • в поле Адрес электронной почты укажите полный адрес вашего электронного ящика, например, email@example.com;
  • в поле Отображать имя в отправленных сообщениях укажите имя, под которым вас будут видеть получатели писем;

Также вы можете указать пароль к данному почтовому ящику и установить флажок Запомнить пароль

Обращаем внимание, что хранение паролей в почтовом клиенте может привести к их краже и использованию вашего почтового ящика для противоправных действий

Установите флажок «Настроить параметры сервера вручную» и нажмите Далее.

3. В появившемся окне укажите параметры сервера:

из списка Тип сервера выберите наиболее подходящий протокол работы с почтой:

    • IMAP – вся почта хранится на сервере. Выберите IMAP в случае, если вы планируете работать с почтой с нескольких устройств и через веб-интерфейс.
    • POP3 – почта скачивается с почтового сервера. Выберите POP3, если работа с почтой планируется только с одного устройства.
  • в полях Адрес сервера для входящей и исходящей почты укажите адрес mail.nic.ru;
  • в поле Имя пользователя для входа укажите полное имя вашего почтового ящика;
  • Установите флажок Требуется проверка подлинности;
  • Отметьте пункты Требуется безопасное соединение.

В случае, если ваш интернет-провайдер блокирует какие-либо порты, вы можете использовать альтернативные.
Для подключения к почтовому серверу доступны следующие порты:

    • IMAP: шифрованное подключение SSL — 993, без шифрования — 143
    • SMTP: шифрованное подключение SSL — 465, без шифрования — 587
    • POP3: шифрованное подключение SSL — 995, без шифрования — 110

После внесения изменений нажмите Далее.

4. Вы успешно ввели все сведения, необходимые для создания учетной записи. Чтобы закрыть окно мастера и начать работу с почтой, нажмите кнопку Готово.

В случае появления сообщения о проверке сертификата безопасности просто нажмите Да.

Конфигурация

После того, как вы установили Mutt с выбранным набором USE-флагов, единственный необходимый шаг – создать файл .muttrc. Примеры muttrc-файлов можно найти во многих местах в Интернете, а также в документации по Mutt. В каталоге /usr/share/doc/mutt-<version>/samples можно найти некоторые примеры файлов muttrc из официальной поставки. Ниже показан очень маленький файл .muttrc для аккаунта с использованием протокола IMAP и доставкой почты по SMTP. Он также активирует подпись электронной почты посредством gpg с использованием бэкэнда gpgme.

.muttrc

Файл Пример файла .muttrc

ЗаметкаБудет хорошей практикой разобраться со всеми настройками из примера конфигурационного файла выше. Есть гораздо больше настроек, а некоторые настройки могут не совпадать с вашими. Помните это, когда сначала вам покажется, что Mutt работает не так, как вам хочется.

Пример .muttrc, показанный выше, настраивает ваш аккаунт IMAP, использует SMTP сервер для передачи почты, сохраняет ее в кэше в /var/tmp/.mutt, читает известные алиасы адресов (думайте об этом как об адресной книге) из файла ~/.aliases и добавляет подпись из ~/.signature при создании новой почты. Для серверов IMAP может быть необходимо изменить каталоги для отправляемой, полученной и задержанной почты, так как каталоги Sent и Drafts могут находиться внутри каталога, называемого INBOX. Просто попробовав Mutt, вы без труда определите, так ли это в вашем случае.

Как только вы настроили .muttrc, вы готовы запустить Mutt, просто набрав mutt. Если вы ввели правильный URL-адрес сервера IMAP, Mutt запросит пароль, а затем загрузит все сообщения. Заметьте, что в первый раз вход в ваш почтовый ящик может занять много времени, если у вас есть много сообщений, так как кэш заголовков Mutt пока пуст. Если все получится, то вы окажетесь в вашем почтовом ящике IMAP, готовом к работе.

Навигация достаточно интуитивна, например, может читать сообщения просто нажимая Template:Ket или пробел. Mutt достаточно похож на Vim в том плане, что он использует нажатия клавиш для выполнения большинства своих действий. Лучше всего прочитать документацию по Mutt, чтобы узнать все существующие функции (либо просто нажмите ? в Mutt), а также, чтобы узнать, какие клавиши нужно нажать, чтобы их вызвать (либо, к какой клавише вы бы хотели их привязать). Некоторые важные клавиши это m (от message) для написания нового сообщения, q для выхода, r для ответа на сообщение, s для сохранения и p для печати.

.mailcap

Одна из возможностей, которые есть в Mutt, но которой все ещё нет в сегодняшних самых продвинутых клиентов электронной почты – это возможность отображать вложения прямо в самой программе, с помощью какого-либо просмотрщика. Директива в файле .muttrc говорит Mutt, какие вложения (согласно их типу MIME) нужно таким образом отображать. Чтобы определить, как это сделать, Mutt использует файлы mailcap, где находит, как отображать конкретные типы MIME. Обычно общесистемного файла mailcap здесь недостаточно, так что вы можете создать свой файл ~/.mailcap, и поместить туда что-либо для , чтобы Mutt мог отображать их в самой программе.

В примере выше для файла .muttrc, включен для файлов и . Эти два вида файлов показывают большую полезность данной возможности, так как это означает, что заметки, присланные вам в виде файлов doc теперь полностью читаемы без необходимости сохранять вложение, и открывать его в LibreOffice. Вместо этого, текст показывается в прямо в программе чтения сообщений, если, конечно, у вас есть соответствующая запись в вашем файле ~/.mailcap.

Файл Пример файла .mailcap

application/msword; antiword '%s'; copiousoutput; description=Word Document;
nametemplate=%s.doc
application/pdf; pdftotext '%s' -; copiousoutput; description=PDF Document;
nametemplate=%s.pdf

3.2 Defining/Using aliases

Usage: key address

It’s usually very cumbersome to remember or type out the address of someone
you are communicating with. Mutt allows you to create «aliases» which map
a short string to a full address.

Note: if you want to create an alias for a group (by specifying more than
one address), you must separate the addresses with a comma («,»).

To remove an alias or aliases:

addr

Unlike other mailers, Mutt doesn’t require aliases to be defined
in a special file. The command can appear anywhere in
a configuration file, as long as this file is
. Consequently, you can have multiple alias files, or
you can have all aliases defined in your muttrc.

On the other hand, the

function can use only one file, the one pointed to by the
variable (which is
by default). This file is not special either,
in the sense that Mutt will happily append aliases to any file, but in
order for the new aliases to take effect you need to explicitly
this file too.

For example:

To use aliases, you merely use the alias at any place in mutt where mutt
prompts for addresses, such as the To: or Cc: prompt. You can
also enter aliases in your editor at the appropriate headers if you have the
variable set.

In addition, at the various address prompts, you can use the tab character
to expand a partial alias to the full alias. If there are multiple matches,
mutt will bring up a menu with the matching aliases. In order to be
presented with the full list of aliases, you must hit tab with out a partial
alias, such as at the beginning of the prompt or after a comma denoting
multiple addresses.

In the alias menu, you can select as many aliases as you want with the
select-entry key (default: RET), and use the exit key
(default: q) to return to the address prompt.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *