Msmtp network read error the operation timed out

I've filed a report against msmtp, but msmtp devs think it's an issue with gnutls. Do you guys have an idea what's wrong here? Below is...
Skip to content



Open


Issue created Dec 07, 2018 by Florian Pritz@Bluewind0

msmtp unable to send mail with gnutls 3.6.5. TLS1.3 issue?

I’ve filed a report against msmtp, but msmtp devs think it’s an issue with gnutls. Do you guys have an idea what’s wrong here?

Below is a copy of the inital bug I filed with msmtp. In case you want to look at the original, it’s here: https://gitlab.marlam.de/marlam/msmtp/issues/21


When trying to send mails to a postfix server with TLS 1.3 support the TLS connection dies after sending the second EHLO.

The only error I see in the msmtp —debug output is this:

msmtp: cannot read from TLS connection: the operation timed out

I see the problem on my Arch Linux client with msmtp 1.8.0-2 and gnutls 3.6.5-1. With gnutls 3.5.19-2 I do not see the issue. Sadly we don’t have any versions in-between to test with. The server is also Arch Linux with postfix 3.3.1-4 and openssl 1.1.1-1.

Using gnutls-cli --starttls 587 $server works just fine and I see the reply to the second EHLO, which is missing in the msmtp --debug output. If you want to test it yourself, feel free to connect to mail.server-speed.net on port 587 with arbitrary credentials. It appears that the issue happens well before the login.

The output I get with GNUTLS_DEBUG_LEVEL=6 msmtp --debug is rather long and I don’t want to leak any private information. If you cannot reproduce the issue, please tell me what else you want to know. Here’s the part at the end:

TLS certificate information:
    Owner:
        Common Name: mail.server-speed.net
    Issuer:
        Common Name: Let's Encrypt Authority X3
        Organization: Let's Encrypt
        Country: US
    Validity:
        Activation time: Sat 27 Oct 2018 12:25:08 AM CEST
        Expiration time: Thu 24 Jan 2019 11:25:08 PM CET
    Fingerprints:
        SHA256: 7B:76:B8:0A:FA:E4:AE:00:B6:8F:24:0E:59:3E:11:BB:67:8F:AC:89:F2:65:0E:4B:BB:4D:12:E4:CB:DD:64:FE
        SHA1 (deprecated): BA:83:63:D4:47:65:88:62:1D:5A:5E:73:87:C0:E6:5C:D3:31:AC:D0
gnutls[5]: REC[0x5604f0be1070]: Preparing Packet Application Data(23) with length: 16 and min pad: 0
gnutls[5]: REC[0x5604f0be1070]: Sent Packet[1] Application Data(23) in epoch 2 and length: 38
--> EHLO localhost
gnutls[5]: REC[0x5604f0be1070]: SSL 3.3 Application Data packet received. Epoch 2, length: 250
gnutls[5]: REC[0x5604f0be1070]: Expected Packet Application Data(23)
gnutls[5]: REC[0x5604f0be1070]: Received Packet Application Data(23) with length: 250
gnutls[5]: REC[0x5604f0be1070]: Decrypted Packet[0] Handshake(22) with length: 233
gnutls[3]: ASSERT: buffers.c[get_last_packet]:1171
gnutls[4]: HSK[0x5604f0be1070]: NEW SESSION TICKET (4) was received. Length 229[229], frag offset 0, frag length: 229, sequence: 0
gnutls[3]: ASSERT: buffers.c[_gnutls_handshake_io_recv_int]:1431
gnutls[4]: HSK[0x5604f0be1070]: parsing session ticket message
gnutls[3]: ASSERT: record.c[_gnutls_recv_in_buffers]:1560
gnutls[3]: ASSERT: record.c[_gnutls_recv_int]:1759
gnutls[3]: ASSERT: buffers.c[_gnutls_io_write_flush]:696
gnutls[5]: REC: Sending Alert[1|0] - Close notify
gnutls[5]: REC[0x5604f0be1070]: Preparing Packet Alert(21) with length: 2 and min pad: 0
gnutls[5]: REC[0x5604f0be1070]: Sent Packet[2] Alert(21) in epoch 2 and length: 24
gnutls[5]: REC[0x5604f0be1070]: Start of epoch cleanup
gnutls[5]: REC[0x5604f0be1070]: End of epoch cleanup
gnutls[5]: REC[0x5604f0be1070]: Epoch #2 freed
msmtp: cannot read from TLS connection: the operation timed out

Also here’s my msmtp config:

defaults
auth plain
tls on
tls_starttls on
tls_certcheck on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

account flo
host mail.server-speed.net
port 587
from bluewind@xinu.at
user mail-flo
passwordeval getpw-single msmtp3

account default : flo

 

Нашелся один агент с интервалом 1. Отключил его, но это не помогло. :(

 

Centos 6.2 правда с не обновленным ядром. Использую веб-окружение. Николай а не подскажете как реализовать первые два пункта описанные вами?

 

Николай здравствуйте. Возникла непонятная проблема: обновляю продукт до последней версии и проседает производительность. Если меняю Zend Optimizaer на APC то все более менее приходит в норму. С чем может быть связана данная проблема?

 

То что я получаю в логах apache и msmtp приведено в сообщении №167.
Проблема в следующем: при заполнении на сайте пользователем формы ему на почту приходит уведомление. Данные уведомления ходя через раз, либо не приходят совсем, либо с задержкой минут в двадцать. Данные ошибки стали проявляться после перехода организации на новый почтовый сервер.

НО(тут стоит вздрогнуть :)): обычный php скрипт с функцией mail зацикленный для теста отсылает 200-400 сообщений и никаких проблем — все проходит.

Если правильно понял что такое тикет то: 269808

 

Возникли проблемы при использовании msmtp. В ТП сказали, что msmtp в принципе работает некоректно.  В таком случае у меня два вопроса: что можно использовать в качестве альтернативы? Зачем по умолчанию использовать неправильное решение?

 

Пользователь 99310

Посетитель

Сообщений: 59
Баллов: 4
Регистрация: 19.08.2011

#

09.02.2012 20:33:54

Возникли проблемы  с msmtp: Исходящая почта работает некорректно. Сценарий такой: первое письмо уходит нормально. При отправке второго намертво вешает сайт. Либо последующие письма просто не уходят.

В логах Apache:

Код
[Thu Feb 09 16:52:39 2012] [notice] Apache/2.2.15 (Unix) mod_rpaf/0.6 PHP/5.3.8-ZS5.5.0 configured -- resuming normal operations
[Thu Feb 09 16:52:54 2012] [error] server reached MaxClients setting, consider raising the MaxClients setting
msmtp: network read error: Connection reset by peer
msmtp: could not send mail (account default from /home/bitrix/.msmtprc)
msmtp: network read error: Connection reset by peer
msmtp: could not send mail (account default from /home/bitrix/.msmtprc)
msmtp: network read error: Connection reset by peer
msmtp: could not send mail (account default from /home/bitrix/.msmtprc)

В логах  msmtp:

Код
Feb 09 17:20:14 host=mail.blabla.ru tls=off auth=on user=tern from=bla@mail.ru recipients=...........@yandex.ru,...............@rmail.ru errormsg='network read error: Connection reset by peer' exitcode=EX_IOERR
Feb 09 17:20:14 host=mail.blabla.ru tls=off auth=on user=tern from=bla@mail.ru recipients=...........@yandex.ru,...............@mail.ru errormsg='network read error: Connection reset by peer' exitcode=EX_IOERR

Конфиг msmtp:

Код
account default
logfile /home/bitrix/.msmtp.log
host mail.blabla.ru
port 25
from .............@mail.ru
auth login
user xxx
password xxx

В чем может быть проблема?

Перейти  
 

 

to lexsed: процесс установки описан в шапке данной темы. :)

 

Пользователь 99310

Посетитель

Сообщений: 59
Баллов: 4
Регистрация: 19.08.2011

#

23.01.2012 22:34:03

теперь в логах:  

Код
msmtp: /home/bitrix/.msmtprc: must have no more than user read/write permissions

после chmod 0600  /home/bitrix/.msmtprc почта начала ходить, единственное — непонятные задержки при отправлении.
Подскажите что можно сделать с данной ошибкой

Код
server reached MaxClients setting, consider raising the MaxClients setting

Перейти  
 

 

Пользователь 99310

Посетитель

Сообщений: 59
Баллов: 4
Регистрация: 19.08.2011

#

23.01.2012 17:58:35

1. Есть2. Есть, плюс:

Код
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = mail.moscow.ru
; http://php.net/smtp-port
smtp_port = 25

3.

Код
[Mon Jan 23 16:05:37 2012] [notice] Apache/2.2.15 (Unix) mod_rpaf/0.6 PHP/5.3.8-ZS5.5.0 configured -- resuming normal operations
[Mon Jan 23 16:05:43 2012] [error] server reached MaxClients setting, consider raising the MaxClients setting
msmtp: /home/bitrix/.msmtprc: must be owned by you
msmtp: /home/bitrix/.msmtprc: must be owned by you 

Я так понимаю симптом —

Код
 msmtp: /home/bitrix/.msmtprc: must be owned by you

Что можно предпринять?

Перейти  
 

 

Пользователь 99310

Посетитель

Сообщений: 59
Баллов: 4
Регистрация: 19.08.2011

#

23.01.2012 17:31:03

Код
-rwxrwxrwx   1 Admin  bitrix   6556 Янв 23 17:18 .msmtp.log
-rwxrwxrwx   1 Admin  bitrix    150 Ноя 14 14:36 .msmtprc
-rwxrwxrwx   1 Admin  bitrix    140 Ноя 14 14:31 .msmtprc~

проверка: » Функция mail не работает, свяжитесь с администрацией хостинга «
в php.ini что то должно быть настроено?

Перейти  
 

 

Centos 6.2 +  BitrixEnv 3.0, не работает msmtp. В логе чисто. Одно время почта ходила нормально. После перезагрузки сервера не могу добиться работы msmtp. «Service sendmail stop|start|restart» получаю «нераспознанная служба». Подскажите пожалуйста в чем может быть затык?

 

Если не затруднит то  вышлите пожалуйста.

 

Здравствуйте. Подскажите пожалуйста с чем может быть связано возникновение данной ошибки:

http://repos.1c-bitrix.ru/yum/el//i386/repodata/repomd.xml:

[Errno 14] PYCURL ERROR 22 — «The requested URL returned error: 403»
Trying other mirror.
Error: Cannot retrieve repository metadata (repomd.xml) for repository: bitrix. Please verify its path and try again

 

Благодарю за совет. Но хотелось бы найти решение проблемы в рамках доступных мне инструментов. Допустим при переносе баз между двумя машинами на Windows  с установленным на обоих ZendServer я не испытываю никаких проблем (базы и экспортируются и импортируются абсолютно нормально по средствам того же phpmyadmin). При переносе из под Windows на Linux ( веб-окружение ) я получаю описанные ошибки. Плюс ко всему Navicat — продукт коммерческий, что сводит на нет возможность его использования.

 

Здравствуйте. С огромным удовольствием использую Ваше веб-окружение. Но недавно столкнулся с одной проблемой. При переносе баз данных средствами phpmyadmin (sypex) получаю ошибку:

phpmyadmin

и

sypex

. Подскажите пожалуйста, что можно предпринять в данной ситуации? К сожалению средствами резервного копирования «Битрикс» воспользоваться нет возможности.

 

В общем то я так и сделал. Но ощущение что удалил что то нужное таки осталась))))

 

Пользователь 99310

Посетитель

Сообщений: 59
Баллов: 4
Регистрация: 19.08.2011

#

06.09.2011 11:17:19

Dios Dios спасибо за помощь. Еще если не сложно: вторым вылезает столбец с заполнением «Предприятие» — он тут совсем не нужен). Как можно убрать?

Скриншот

P.S.: С «Предприятием» разобрался.
Почему то выдает ошибку в коде (14 строка) —

Код
<? echo GetMessage(arProperty["PROPERTY_CODE"]); ?> 

Перейти  
 

 

Компонент скорей всего стандартный. Сам оригинал шаблона позволял выводить подобие телефонной книги(с возможность перехода к биографии(детальное описание) человека).

 

Пользователь 99310

Посетитель

Сообщений: 59
Баллов: 4
Регистрация: 19.08.2011

#

06.09.2011 09:34:47

1. Шаблон компонента news.list (самописный)

Вот весь код:

Код
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>

<div class="phone_list_2">
        <?foreach($arResult["SECTIONS"] as $arSection):?>
                <h3><?=($arSection["NAME"])?$arSection["NAME"]:"Руководство"?></h3>
                <?foreach($arSection["ITEMS"] as $arItem):?>
                <div class="phone_item">
                        <div class="official_telephone">
                                <?if($arItem["DISPLAY_PROPERTIES"]["PHONE"]["VALUE"]):?>
                                        <i>тел.:</i> <?=$arItem["DISPLAY_PROPERTIES"]["PHONE"]["VALUE"]?><br />
                                <?endif>
                        </div>
                        <div class="name_ph"><a href="<?=$arItem["DETAIL_PAGE_URL"]?>"><?=$arItem["NAME"]?></a></div>
                        <?if($arItem["DISPLAY_PROPERTIES"]["JOB"]["VALUE"]):?>
                                <div class="desc_ph"><?=$arItem["DISPLAY_PROPERTIES"]["JOB"]["VALUE"]?></div>
                        <?endif;?>
                        <div class="clear_phone"></div>
                </div>
                <?endforeach;?>
        <?endforeach;?>

</div>

В итоге должна получиться таблица из четырех столбцов:
«Наименование» «ФИО» «Адрес» «Телефон».
Переход к детальному просмотру здесь не нужен (<a href=»<?=$arItem[«DETAIL_PAGE_URL»]?>)

Перейти  
 

 

А как правильно? Подскажите пожалуйста.

 

Пользователь 99310

Посетитель

Сообщений: 59
Баллов: 4
Регистрация: 19.08.2011

#

05.09.2011 19:13:13

Здравствуйте. Необходимо вывести информацию раздела инфоблока в виде таблицы: Шаблон инфоблока

Код
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>

<div class="phone_list_2">
        <?foreach($arResult["SECTIONS"] as $arSection):?>
                <h3><?=($arSection["NAME"])?$arSection["NAME"]:"Руководство"?></h3>
                <?foreach($arSection["ITEMS"] as $arItem):?>
                <div class="phone_item">
                        <div class="official_telephone">
                                <?if($arItem["DISPLAY_PROPERTIES"]["PHONE"]["VALUE"]):?>
                                        <i>тел.:</i> <?=$arItem["DISPLAY_PROPERTIES"]["PHONE"]["VALUE"]?
                        <?endif;?>
                        <div class="clear_phone"></div>

У меня получается вот такой вариант:

Код
[CODE]<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>

<div class="phone_list_2">
        <?foreach($arResult["SECTIONS"] as $arSection):?>
<h3><?=($arSection["NAME"])?$arSection["NAME"]:"Руководство"?></h3> \ заголовок убираю
                <?foreach($arSection["ITEMS"] as $arItem):?>
                <div class="phone_item">
                        <div class="official_telephone">
<table>
<tbody>
                                <tr> <td><?if($arItem["DISPLAY_PROPERTIES"]["PHONE"]["VALUE"]):?>
                                         <?=$arItem["DISPLAY_PROPERTIES"]["PHONE"]["VALUE"]?
                        <?endif;?>
                                </td></tr>

                        <div class="clear_phone"></div>
<?endforeach;?>
        <?endforeach;?>

Вапрос чайника: На сколько корректо решена задача? (Нехорошее чувство, что делаю что то не так).
И никак не могу выровнять в ячейке содержимое по вертикали(valign не помогает)

Заранее благодарен!

Перейти  
 

Настройка msmtp (версия 1.4.28) в debian. В чем ошибка?

Никак не могу заставить этого «почтальона» отправить письмо:

Собственно вот сам конфиг
defaults
account default
host smtp.mail.ru
port 465
protocol smtp
auth on
tls on
tls_starttls on
tls_certcheck off
user ******@mail.ru
password *
from ******@mail.ru
logfile msmtp.log
timeout 15

Пытаюсь отправить сообщение такой командой:
echo «test» | msmtp -d получатель@mail.ru
Пишет следующее:
loaded system configuration file /etc/msmtprc
ignoring user configuration file /root/.msmtprc: No such file or directory
falling back to default account
using account default from /etc/msmtprc
host = smtp.mail.ru
port = 465
timeout = 15 seconds
protocol = smtp
domain = localhost
auth = choose
user = wiren.board@mail.com
password = *
passwordeval = (not set)
ntlmdomain = (not set)
tls = on
tls_starttls = on
tls_trust_file = (not set)
tls_crl_file = (not set)
tls_fingerprint = (not set)
tls_key_file = (not set)
tls_cert_file = (not set)
tls_certcheck = off
tls_force_sslv3 = off
tls_min_dh_prime_bits = (not set)
tls_priorities = (not set)
auto_from = off
maildomain = (not set)
from = wiren.board@mail.ru
dsn_notify = (not set)
dsn_return = (not set)
keepbcc = off
logfile = msmtp.log
syslog = (not set)
aliases = (not set)
reading recipients from the command line

И тут бесконечное ожидание.

Ничего не происходит, если не обозначить таймаут. При таймауте пишет
reading recipients from the command line
sendmail: network read error: the operation timed out
sendmail: could not send mail (account default from /etc/msmtprc)

Источник

msmtp

msmtp is a very simple and easy to use SMTP client with fairly complete sendmail compatibility.

Installation

Install the msmtp package. Additionally, install msmtp-mta , which creates a sendmail alias to msmtp.

Basic setup

Since msmtp version 1.8.6 you can place your user configuration either at

/.msmtprc or $XDG_CONFIG_HOME/msmtp/config . The following is an example of a msmtp configuration (the file is based on the per-user example file located at /usr/share/doc/msmtp/msmtprc-user.example ; the system configuration file belongs at /etc/msmtprc and its corresponding example file is located at /usr/share/doc/msmtp/msmtprc-system.example ).

The user configuration file must be explicitly readable/writeable by its owner or msmtp will fail:

To avoid saving the password in plain text in the configuration file, use passwordeval to launch an external program, or see the #Password management section below. This example using Gnu PG is commonly used to perform decryption of a password:

OAuth2 Setup

OAuth2 can be used to securely authenticate msmtp when basic username/password authentication is unsupported by the site configuration or otherwise undesirable.

mailctl

msmtp alone lacks the ability to renew or authorize OAuth2 credentials. A comprehensive solution is using the mailctl utility which provides IMAP/SMTP clients with renewal capabilities and authorization of OAuth2 credentials.

To use mailctl, install mailctl-bin AUR and configure msmtp to use it:

Access token renewal happens automatically in the background transparent to the user.

oauth2token

Install oauth2token AUR and follow its README to configure the account. Run the oauth2create script to obtain and store credentials for each account.

Add auth oauthbearer and passwordeval oauth2get provider account , substituting provider and account with the values you used for oauth2create in your config.

Wrapper on oauth2.py

This is a scripted method, using the msmtp setting oauthbearer for authentication.

Once you have your Gmail API setup, you can implement the wrapper script oauth2token (that employs secret-tool(1) ) or an adaptation of oauth2token (that employs pass).

An msmtp configuration would be adapted thus:

If you comment out the last line, msmtp will request you for the token that oauth2.py provides you, which is normally valid for one hour.

OAuth2 hack

To use XOAUTH2 authentication with Gmail (see official information), you can install the msmtp-oauth2 AUR package. The package does a small hack so that the plain authentication method will send the AUTH XOAUTH2 password instead of the AUTH PLAIN . , effectively disabling plain authentication and enabling XOAUTH2. Your msmtp would be adapted as follows:

The get-gmail-token script can be found from the source files of the msmtp-oauth2 package. See more information on getmail link about how this works. And see Gmail API quickstart for instruction on registering a Gmail APP and authorizing it to access emails.

Using the mail command

To send mails using the mail command you must install the package s-nail , which also provides the mailx command. You will also need to provide a sendmail -compatible MTA, either by installing msmtp-mta (which symlinks sendmail to msmtp ) or by editing /etc/mail.rc to set the sendmail path:

A .msmtprc file will need to be in the home of every user who wants to send mail or alternatively the system wide /etc/msmtprc can be used.

msmtp also understands aliases. Add the following line to the defaults section of msmtprc or your local configuration file:

and create an aliases file in /etc

Test functionality

The account option ( —account=,-a ) tells which account to use as sender:

Or, send both a subject and a body:

Or, with the addresses in a file:

Cronie default email client

This article or section is out of date.

To make Cronie use msmtp rather than sendmail, make sure msmtp-mta is installed, or edit the cronie.service systemd unit:

Then you must tell cronie or msmtp what your email address is, either by:

  1. Add to /etc/msmtprc : and create /etc/aliases : — OR —.
  • Add a MAILTO line to the crontab:

Password management

Passwords for msmtp can be stored in plaintext, encrypted files, or a keyring.

GNOME Keyring

Storing passwords in GNOME Keyring is supported natively in msmtp. Setup the keyring as described on the linked wiki page and install libsecret . Then, store a password by running:

msmtp should now find the password automatically.

GnuPG

The password directive may be omitted. In that case, if the account in question has auth set to a legitimate value other than off , invoking msmtp from an interactive shell will ask for the password before sending mail. msmtp will not prompt if it has been called by another type of application, such as Mutt. For such cases, the —passwordeval parameter can be used to call an external keyring tool like GnuPG.

To do this, set up GnuPG, including gpg-agent to avoid having to enter the password every time. Then, create an encrypted password file for msmtp, as follows. Create a secure directory with 700 permissions located on a tmpfs to avoid writing the unencrypted password to the disk. In that directory create a plain text file with the mail account password. Then, encrypt the file with your private key:

Remove the plain text file and move the encrypted file to the final location, e.g.

Normally this is sufficient for a GUI password prompt to appear when, for example, sending a message from Mutt. If gpg prompt for the passphrase cannot be issued, then start the gpg-agent before. A simple hack to start the agent is to execute a external command in your muttrc using the backtick `command` syntax. For example, you can put something like the following in your muttrc:

Mutt will execute this when it starts, gpg-agent will cache your password, msmtp will be happy and you can send mail.

An alternative is to place passwords in

/.netrc , a file that can act as a common pool for msmtp, OfflineIMAP, and associated tools.

You may store your credentials inside of the pass password manager.

If you are using your main password (which is customarily stored in the first line of your pass file) to login into your SMTP server, you can add the following to your .msmptrc :

If you are using Gmail, and have set up an app password, the following configuration will suit you better. Save your app password inside your pass password file, but with a msmtp: prefix:

Then add the following to your .msmptrc :

In either case, trying to send an email with msmtp will trigger pass , which may ask you for your pass master password if you have not entered it recently.

Miscellaneous

Using msmtp offline

Although msmtp is great, it requires that you be online to use it. This is not ideal for people on laptops with intermittent connections to the Internet or dialup users. Several scripts have been written to remedy this fact, collectively called msmtpqueue.

The scripts are installed under /usr/share/doc/msmtp/msmtpqueue . You might want to copy the scripts to a convenient location on your computer, ( /usr/local/bin is a good choice).

Finally, change your MUA to use msmtp-enqueue.sh instead of msmtp when sending e-mail. By default, queued messages will be stored in

/.msmtpqueue . To change this location, change the QUEUEDIR=$HOME/.msmtpqueue line in the scripts (or delete the line, and export the QUEUEDIR variable in .bash_profile like so: export QUEUEDIR=»$XDG_DATA_HOME/msmtpqueue» ).

When you want to send any mail that you have created and queued up run:

Adding /usr/local/bin to your PATH can save you some keystrokes if you are doing it manually. The README file that comes with the scripts has some handy information, reading it is recommended.

Vim syntax highlighting

The msmtp source distribution includes an msmtprc syntax-highlighting script for Vim, which is available at /usr/share/vim/vimfiles/syntax/msmtp.vim . The filetype is not detected automatically. The easiest way to enable it is by adding a modeline at the top or bottom of the file(s), i.e.:

Send mail with PHP using msmtp

Look for sendmail_path option in your php.ini and edit like this:

Note that you can not use a user configuration file (ie: one under

/) if you plan on using msmtp as a sendmail replacement with php or something similar. In that case just create /etc/msmtprc, and remove your user configuration (or not if you plan on using it for something else). Also make sure it is readable by whatever you are using it with (php, django, etc. ).

From the msmtp manual: Accounts defined in the user configuration file override accounts from the system configuration file. The user configuration file must have no more permissions than user read/write

So it is impossible to have a conf file under

/ and have it still be readable by the php user.

To test it place this file in your php enabled server or using php-cli.

php-fpm will fail to send mails and logs the warning: PHP Warning: mail(mail.log): failed to open stream unless you set the permissions of your /etc/msmtprc to user read/write (600).

Troubleshooting

Issues with TLS

If you see the following message:

It probably means your tls_trust_file is not right.

Just follow the fine manual. It explains you how to find out the server certificate issuer of a given smtp server. Then you can explore the /usr/share/ca-certificates/ directory to find out if by any chance, the certificate you need is there. If not, you will have to get the certificate on your own. If you are using your own certificate, you can make msmtp trust it by adding the following to your

If you are trying to send mail through Gmail and are receiving this error, have a look at this thread or just use the second Gmail example above.

If you are completely desperate, but are 100% sure you are communicating with the right server, you can always temporarily disable the cert check:

If you see the following message:

You may be affected by this bug. Recompile with —with-ssl=openssl (msmtp is compiled with GnuTLS by default).

Server sent empty reply

If you get a «server sent empty reply» error, this probably means the mail server does not support STARTTLS over port 587, but requires TLS over port 465.

To let msmtp use TLS over port 465, add the following line to

Zoho SMTP server

It can also happen on Zoho SMTP servers when the mail has no blank line between mail headers and mail body (see Debian bug #917260). The solution to this is to add an extra space in between:

Issues with GSSAPI

If you get the following error

Try changing your auth setting to plain, instead of gssapi in your .msmtprc file [1]:

Источник

msmtp — Man Page

Examples (TL;DR)

  • Send an email using the default account configured in

/.msmtprc : echo » Hello world » | msmtp to@example.org
Send an email using a specific account configured in

/.msmtprc : echo » Hello world » | msmtp —account= account_name to@example.org
Send an email without a configured account. The password should be specified in the

/.msmtprc file: echo » Hello world » | msmtp —host= localhost —port= 999 —from= from@example.org to@example.org

Synopsis

msmtp [option. ] [—] recipient.
msmtp [option. ] -t [—] [recipient. ]

Server information mode:

msmtp [option. ] —serverinfo

Remote Message Queue Starting mode:

Description

In the default sendmail mode, msmtp reads a mail from standard input and sends it to an SMTP server for delivery.
In server information mode, msmtp prints information about an SMTP server.
In Remote Message Queue Starting mode, msmtp sends a Remote Message Queue Starting request for a host, domain, or queue to an SMTP server.

Exit Status

The standard sendmail exit status codes are used, as defined in sysexits.h.

Options

Options override configuration file settings.
They are compatible with sendmail where appropriate.

General options —version

Print version information, including information about the libraries used.

Print the configuration settings that would be used, but do not take further action. An asterisk (`*’) will be printed instead of your password.

Print lots of debugging information, including the whole conversation with the SMTP server. Be careful with this option: the (potentially dangerous) output will not be sanitized, and your password may get printed in an easily decodable format!

Changing the mode of operation —configure=mailaddress

Generate a configuration for the given mail address and print it. This can be modified or copied unchanged to the configuration file. Note that this only works for mail domains that publish appropriate SRV records; see RFC 8314.

Print information about the SMTP server and exit. This includes information about supported features (mail size limit, authentication, TLS, DSN, . ) and about the TLS certificate (if TLS is active).

Send a Remote Message Queue Starting request for the given host, domain, or queue to the SMTP server and exit.

Configuration options -C, —file=filename

Use the given file instead of

/.msmtprc or $XDG_CONFIG_HOME/msmtp/config as the user configuration file.

Use the given account instead of the account named «default». The settings of this account may be changed with command line options. This option cannot be used together with the —host option.

Use this SMTP server with settings from the command line; do not use any configuration file data. This option cannot be used together with the —account option.

Set the port number to connect to. See the port command.

Set or unset an IP address to bind the socket to. See the source_ip command.

Set or unset a SOCKS proxy to use. See the proxy_host command.

Set or unset a port number for the proxy host. See the proxy_port command.

Set or unset a local unix domain socket name to connect to. See the socket command.

Set or unset a network timeout, in seconds. See the timeout command.

Set the protocol. See the protocol command.

Set the argument of the SMTP EHLO (or LMTP LHLO) command. See the domain command.

Enable or disable authentication and optionally choose the method. See the auth command.

Set or unset the user name for authentication. See the user command.

Evaluate password for authentication. See the passwordeval command.

Enable or disable TLS/SSL. See the tls command.

Enable or disable STARTTLS for TLS. See the tls_starttls command.

Set or unset a trust file for TLS. See the tls_trust_file command.

Deprecated. Set or unset a certificate revocation list (CRL) file for TLS. See the tls_crl_file command.

Set or unset the fingerprint of a trusted TLS certificate. See the tls_fingerprint command.

Set or unset a key file for TLS. See the tls_key_file command.

Set or unset a cert file for TLS. See the tls_cert_file command.

Enable or disable server certificate checks for TLS. See the tls_certcheck command.

Set or unset TLS priorities. See the tls_priorities command.

Set or unset override for TLS host verification. See the tls_host_override command.

Deprecated, use —tls-priorities instead. Set or unset minimum bit size of the Diffie-Hellman (DH) prime. See the tls_min_dh_prime_bits command.

Options specific to sendmail mode -f, —from=address

Set the envelope-from address.
If no account was chosen yet (with —account or —host), this option will choose the first account that has the given envelope-from address (set with the from command). If no such account is found, «default» is used.
See the from and allow_from_override commands.

Set or unset DSN notification conditions. See the dsn_notify command.

Set or unset the DSN notification amount. See the dsn_return command. Note that hdrs is accepted as an alias for headers to be compatible with sendmail.

Set From header handling. See the set_from_header command.

Set Date header handling. See the set_date_header command.

Set Message-ID header handling. See the set_msgid_header command.

Enable or disable the removal of Bcc headers. See the remove_bcc_headers command.

Enable or disable the replacement of To/Cc/Bcc with «To: undisclosed-recipients:;». See the undisclosed_recipients command.

Set or unset the log file. See the logfile command.

Set or unset the log file time format. See the logfile_time_format command.

Enable or disable syslog logging. See the syslog command.

Read recipient addresses from the To, Cc, and Bcc headers of the mail in addition to the recipients given on the command line. If any Resent- headers are present, then the addresses from any Resent-To, Resent-Cc, and Resent-Bcc headers in the first block of Resent- headers are used instead.

Read the envelope from address from the From header of the mail.

Set or unset an aliases file. See the aliases command.

Msmtp adds a From header to mails that lack it, using the envelope from address. This option allows one to set a full name to be used in that header.

Obsolete. See the auto_from command.

Obsolete. See the maildomain command.

This marks the end of options. All following arguments will be treated as recipient addresses, even if they start with a `-‘.

The following options are accepted but ignored for sendmail compatibility:
-Btype, -bm, -G, -hN, -i, -L tag, -m, -n, -O option=value, -ox value

Usage

A suggestion for a suitable configuration file can be generated using the —configure option. Normally, a system wide configuration file and/or a user configuration file contain information about which SMTP server to use and how to use it, but all settings can also be configured on the command line.
The information about SMTP servers is organized in accounts. Each account describes one SMTP server: host name, authentication settings, TLS settings, and so on. Each configuration file can define multiple accounts.

The user can choose which account to use in one of three ways:

Use the given account. Command line settings override configuration file settings.

Use only the settings from the command line; do not use any configuration file data.

—from=address or —read-envelope-from

Choose the first account from the system or user configuration file that has a matching envelope-from address as specified by a from command. This works only when neither —account nor —host is used.
Subadresses are supported. For example, the envelope from address user+detail@example.com will match the account for user@example.com.
Furthermore, the envelope-from address of the account may be a wildcard pattern. See the from command.

If none of the above options is used (or if no account has a matching from command), then the account «default» is used.

Msmtp transmits mails unaltered to the SMTP server, with the following exceptions:
— The Bcc header(s) will be removed. This behavior can be changed with the remove_bcc_headers command and —remove-bcc-headers option.
— A From header will be added if the mail does not have one. This can be changed with the set_from_header command and —set-from-header option. The header will use the envelope from address and optionally a full name set with the -F option.
— A Date header will be added if the mail does not have one. This can be changed with the set_date_header command and —set-date-header option.
— A Message-ID header will be added if the mail does not have one. This can be changed with the set_msg_header command and —set-msgid-header option.
— When undisclosed_recipients is set, the original To, Cc, and Bcc headers are removed and replaced with «To: undisclosed-recipients:;».

Skip to the Examples section for a quick start.

Configuration Files

If it exists and is readable, a system wide configuration file SYSCONFDIR/msmtprc will be loaded, where SYSCONFDIR depends on your platform. Use —version to find out which directory is used.
If it exists and is readable, a user configuration file will be loaded (

/.msmtprc will be tried first followed by $XDG_CONFIG_HOME/msmtp/config by default, but see —version). Accounts defined in the user configuration file override accounts from the system configuration file.
Configuration data from either file can be changed by command line options.

A configuration file is a simple text file. Empty lines and comment lines (whose first non-blank character is `#’) are ignored.
Every other line must contain a command and may contain an argument to that command.
The argument may be enclosed in double quotes («), for example if its first or last character is a blank.
If a file name starts with the tilde (

), this tilde will be replaced by $HOME. If a command accepts the argument on, it also accepts an empty argument and treats that as if it was on.
Commands are organized in accounts. Each account starts with the account command and defines the settings for one SMTP account.

Skip to the Examples section for a quick start.

Commands are as follows:

Set defaults. The following configuration commands will set default values for all following account definitions in the current configuration file.

Start a new account definition with the given name. The current default values are filled in.
If a colon and a list of previously defined accounts is given after the account name, the new account, with the filled in default values, will inherit all settings from the accounts in the list.

Replace the current configuration file line with the first line of the output (stdout) of the command cmd. This can be used to decrypt settings or to create them via scripts. For example, eval echo host localhost replaces the current line with host localhost.
The cmd command must not mess with standard input; if in doubt, append host hostname

The SMTP server to send the mail to. The argument may be a host name or a network address. Every account definition must contain this command.

The port that the SMTP server listens on. The default is 25 («smtp»), unless TLS without STARTTLS is used, in which case it is 465 («smtps»).

Set a source IP address to bind the outgoing connection to. Useful only in special cases on multi-home systems. An empty argument disables this.

Use a SOCKS proxy. All network traffic will go through this proxy host, including DNS queries, except for a DNS query that might be necessary to resolve the proxy host name itself (this can be avoided by using an IP address as proxy host name). An empty hostname argument disables proxy usage. The supported SOCKS protocol version is 5. If you want to use this with Tor, see also «Using msmtp with Tor» below.

Set the port number for the proxy host. An empty number argument resets this to the default port.

Set the file name of a unix domain socket to connect to. This overrides both host/port and proxy_host/proxy_port.

Set or unset a network timeout, in seconds. The argument off means that no timeout will be set, which means that the operating system default will be used.

Set the protocol to use. Currently only SMTP and LMTP are supported. SMTP is the default. See the port command above for default ports.

Use this command to set the argument of the SMTP EHLO (or LMTP LHLO) command. The default is localhost, which is stupid but usually works. Try to change the default if mails get rejected due to anti-SPAM measures. Possible choices are the domain part of your mail address (provider.example for joe@provider.example) or the fully qualified domain name of your host (if available).
The following substitution patterns are supported:
%H will be replaced by $HOSTNAME, or if that fails by the host name of the system.
%C will be replaced by the canonical name of %H.
%M will be replaced by the contents of /etc/mailname (potentially a different directory is used depending on the build configuration; see the output of msmtp —version and look for the location of the system configuration file).

Enable or disable authentication and optionally choose a method to use. The argument on chooses a method automatically.
Usually a user name and a password are used for authentication. The user name is specified in the configuration file with the user command. There are five different methods to specify the password:
1. Add the password to the system key ring. Currently supported key rings are the Gnome key ring and the Mac OS X Keychain. For the Gnome key ring, use the command secret-tool (part of Gnome’s libsecret) to store passwords: secret-tool store —label=msmtp host mail.freemail.example service smtp user joe.smith. On Mac OS X, use the following command: security add-internet-password -s mail.freemail.example -r smtp -a joe.smith -w. In both examples, replace mail.freemail.example with the SMTP server name, and joe.smith with your user name.
2. Store the password in an encrypted files, and use passwordeval to specify a command to decrypt that file, e.g. using GnuPG. See Examples.
3. Store the password in the configuration file using the password command. (Usually it is not considered a good idea to store passwords in cleartext files. If you do it anyway, you must make sure that the file can only be read by yourself.)
4. Store the password in

/.netrc. This method is probably obsolete.
5. Type the password into the terminal when it is required.
It is recommended to use method 1 or 2.
Multiple authentication methods exist. Most servers support only some of them. Historically, sophisticated methods were developed to protect passwords from being sent unencrypted to the server, but nowadays everybody needs TLS anyway, so the simple methods suffice since the whole session is protected. A suitable authentication method is chosen automatically, and when TLS is disabled for some reason, only methods that avoid sending cleartext passwords are considered.
The following user / password methods are supported: plain (a simple cleartext method, with base64 encoding, supported by almost all servers), scram-sha-1 (a method that avoids cleartext passwords), scram-sha-256 (same but with stronger hash), cram-md5 (an obsolete method that avoids cleartext passwords, but is not considered secure anymore), digest-md5 (an overcomplicated obsolete method that avoids cleartext passwords, but is not considered secure anymore), login (a non-standard cleartext method similar to but worse than the plain method), ntlm (an obscure non-standard method that is now considered broken; it sometimes requires a special domain parameter passed via ntlmdomain).
There are currently three authentication methods that are not based on user / password information and have to be chosen manually: oauthbearer or its predecessor xoauth2 (an OAuth2 token from the mail provider is used as the password. See the documentation of your mail provider for details on how to get this token. The passwordeval command can be used to pass the regularly changing tokens into msmtp from a script or an environment variable), external (the authentication happens outside of the protocol, typically by sending a TLS client certificate, and the method merely confirms that this authentication succeeded), and gssapi (the Kerberos framework takes care of secure authentication, only a user name is required).
It depends on the underlying authentication library and its version whether a particular method is supported or not. Use —version to find out which methods are supported.

Set the user name for authentication. An empty argument unsets the user name.

Set the password for authentication. An empty argument unsets the password. Consider using the passwordeval command or a key ring instead of this command, to avoid storing cleartext passwords in the configuration file.

Set the password for authentication to the output (stdout) of the command cmd. This can be used e.g. to decrypt password files on the fly or to query key rings, and thus to avoid storing cleartext passwords.
The cmd command must not mess with standard input; if in doubt, append ntlmdomain [domain]

Set a domain for the ntlm authentication method. This is obsolete.

Enable or disable TLS (also known as SSL) for secured connections.
Transport Layer Security (TLS) «. provides communications privacy over the Internet. The protocol allows client/server applications to communicate in a way that is designed to prevent eavesdropping, tampering, or message forgery» (quote from RFC2246).
A server can use TLS in one of two modes: via a STARTTLS command (the session starts with the normal protocol initialization, and TLS is then started using the protocol’s STARTTLS command), or immediately (TLS is initialized before the normal protocol initialization; this requires a separate port). The first mode is the default, but you can switch to the second mode by disabling tls_starttls.
When TLS is started, the server sends a certificate to identify itself. To verify the server identity, a client program is expected to check that the certificate is formally correct and that it was issued by a Certificate Authority (CA) that the user trusts. (There can also be certificate chains with intermediate CAs.)
The list of trusted CAs is specified using the tls_trust_file command. The default value ist «system» and chooses the system-wide default, but you can also choose the trusted CAs yourself.
A fundamental problem with this is that you need to trust CAs. Like any other organization, a CA can be incompetent, malicious, subverted by bad people, or forced by government agencies to compromise end users without telling them. All of these things happened and continue to happen worldwide. The idea to have central organizations that have to be trusted for your communication to be secure is fundamentally broken.
Instead of putting trust in a CA, you can choose to trust only a single certificate for the server you want to connect to. For that purpose, specify the certificate fingerprint with tls_fingerprint. This makes sure that no man-in-the-middle can fake the identity of the server by presenting you a fraudulent certificate issued by some CA that happens to be in your trust list. However, you have to update the fingerprint whenever the server certificate changes, and you have to make sure that the change is legitimate each time, e.g. when the old certificate expired. This is inconvenient, but it’s the price to pay.
Information about a server certificate can be obtained with —serverinfo —tls —tls-certcheck=off. This includes the issuer CA of the certificate (so you can trust that CA via tls_trust_file), and the fingerprint of the certificate (so you can trust that particular certificate via tls_fingerprint).
TLS also allows the server to verify the identity of the client. For this purpose, the client has to present a certificate issued by a CA that the server trusts. To present that certificate, the client also needs the matching key file. You can set the certificate and key files using tls_cert_file and tls_key_file. This mechanism can also be used to authenticate users, so that traditional user / password authentication is not necessary anymore. See the external mechanism in auth.
You can also use client certificates stored on some external authentication device by specifying GnuTLS device URIs in tls_cert_file and tls_key_file. You can find the correct URIs using p11tool —list-privkeys —login (p11tool is bundled with GnuTLS). If your device requires a PIN to access the data, you can specify that using one of the password mechanisms (e.g. passwordeval, password).

Choose the TLS variant: start TLS from within the session (on, default), or tunnel the session through TLS (off).

Activate server certificate verification using a list of trusted Certification Authorities (CAs). The default is the special value «system», which selects the system default. An empty argument disables trust in CAs. If you select a file, it must be in PEM format, and you should also use tls_crl_file.

Deprecated. This sets a certificate revocation list (CRL) file for TLS, to check for revoked certificates (an empty argument, which is the default, disables this). Nowadays automatic OCSP checks replace CRL file checks.

Set the fingerprint of a single certificate to accept for TLS. This certificate will be trusted regardless of its contents (this overrides tls_trust_file). The fingerprint should be of type SHA256, but can for backwards compatibility also be of type SHA1 or MD5 (please avoid this). The format should be 01:23:45:67. Use —serverinfo —tls —tls-certcheck=off —tls-fingerprint= to get the server certificate fingerprint.

Send a client certificate to the server (use this together with tls_cert_file>). The file must contain the private key of a certificate in PEM format. An empty argument disables this feature.

Send a client certificate to the server (use this together with tls_key_file). The file must contain a certificate in PEM format. An empty argument disables this feature.

Enable or disable checks of the server certificate. They are enabled by default. Disabling them will override tls_trust_file and tls_fingerprint. WARNING: When the checks are disabled, TLS sessions will not be secure!

Set priorities for TLS session parameters. The default is set by the TLS library and can be selected by using an empty argument to this command. The interpretation of the priorities string depends on the TLS library. Use —version to find out which TLS library you use.
For GnuTLS, see the section on Priority Strings in the manual.
For libtls, the priorites string is a space-separated list of parameter strings prefixed with either PROTOCOLS=, CIPHERS=, or ECDHECURVES=. These parameter strings will be passed to the functions tls_config_parse_protocols, tls_config_set_ciphers, and tls_config_set_ecdhecurves. Unrecognized parts of the priorities string will be ignored. Example: «PROTOCOLS=TLSv1.3 CIPHERS=ECDHE-RSA-AES128-SHA256 ECDHECURVES=P-384».

By default, TLS host verification uses the host name given by the host command. This command allows one to use a different host name for verification. This is only useful in special cases.

Deprecated, use tls_priorities instead. Set or unset the minimum number of Diffie-Hellman (DH) prime bits accepted for TLS sessions. The default is set by the TLS library and can be selected by using an empty argument to this command. Only lower the default (for example to 512 bits) if there is no other way to make TLS work with the remote server.

Set the envelope-from address. The following substitution patterns are supported:
%U will be replaced by $USER, or if that fails by $LOGNAME, or if that fails by the login name of the user running msmtp.
%H will be replaced by $HOSTNAME, or if that fails by the host name of the system.
%C will be replaced by the canonical name of %H.
%M will be replaced by the contents of /etc/mailname (potentially a different directory is used depending on the build configuration; see the output of msmtp —version and look for the location of the system configuration file).
Note that the obsolete auto_from command replaces this envelope-from address.
To enforce the use of this envelope-from address and ignore the -f / —from option, see the allow_from_override command.
Furthermore, the envelope-from address may be a wildcard pattern as used for file name matching in the shell. This is the case if it contains one of the characters ?, * or [. This allows a variety of envelope-from addresses given with the —from option to match a single account.

By default, the —from option overrides the from command. Set to off to disable this.

This command sets the condition(s) under which the mail system should send DSN (Delivery Status Notification) messages. The argument off disables explicit DSN requests, which means the mail system decides when to send DSN messages. This is the default. The condition must be never, to never request notification, or a comma separated list (no spaces!) of one or more of the following: failure, to request notification on transmission failure, delay, to be notified of message delays, success, to be notified of successful transmission. The SMTP server must support the DSN extension.

This command controls how much of a mail should be returned in DSN (Delivery Status Notification) messages. The argument off disables explicit DSN requests, which means the mail system decides how much of a mail it returns in DSN messages. This is the default. The amount must be headers, to just return the message headers, or full, to return the full mail. The SMTP server must support the DSN extension.

When to set a From header: auto adds a From header if the mail does not have one (this is the default), on always sets a From header and overrides any existing one, and off never sets a From header.
If the mail server rejects the mail because its From header does not match the envelope-from address (a common anti-spam measure), then you might want to set this option to on.
The From header is created based on the envelope-from address. Disable allow_from_override to prevent programs from setting their own envelope-from address.
For compatibility with older versions, add_missing_from_header [(on|off)] is still supported and corresponds to the auto and off settings.

When to set a Date header: auto adds a Date header if the mail does not have one (this is the default), and off never sets a Date header.
For compatibility with older versions, add_missing_date_header [(on|off)] is still supported and corresponds to the auto and off settings.

When to set a Message-ID header: auto adds a Message-ID header if the mail does not have one (this is the default), and off never sets a Message-ID header.

This command controls whether to remove Bcc headers. The default is to remove them.

When set, the original To, Cc, and Bcc headers of the mail are removed and a single new header line «To: undisclosed-recipients:;» is added. The default setting is off.

An empty argument disables logging (this is the default).
When logging is enabled by choosing a log file, msmtp will append one line to the log file for each mail it tries to send via the account that this log file was chosen for.
The line will include the following information: date and time in the format specified by logfile_time_format, host name of the SMTP server, whether TLS was used, whether authentication was used, authentication user name (only if authentication is used), envelope-from address, recipient addresses, size of the mail as transferred to the server (only if the delivery succeeded), SMTP status code and SMTP error message (only in case of failure and only if available), error message (only in case of failure and only if available), exit code (from sysexits.h; EX_OK indicates success).
If the filename is a dash (-), msmtp prints the log line to the standard output.

Set or unset the log file time format. This will be used as the format string for the strftime() function. An empty argument chooses the default («%b %d %H:%M:%S»).

Enable or disable syslog logging. The facility can be one of LOG_USER, LOG_MAIL, LOG_LOCAL0, . LOG_LOCAL7. The default is LOG_USER.
Each time msmtp tries to send a mail via the account that contains this syslog command, it will log one entry to the syslog service with the chosen facility.
The line will include the following information: host name of the SMTP server, whether TLS was used, whether authentication was used, envelope-from address, recipient addresses, size of the mail as transferred to the server (only if the delivery succeeded), SMTP status code and SMTP error message (only in case of failure and only if available), error message (only in case of failure and only if available), exit code (from sysexits.h; EX_OK indicates success).

Replace local recipients with addresses in the aliases file. The aliases file is a cleartext file containing mappings between a local address and a list of replacement addresses. The mappings are of the form:
local: someone@example.com, person@domain.example
Multiple replacement addresses are separated with commas. Comments start with `#’ and continue to the end of the line.
The local address default has special significance and is matched if the local address is not found in the aliases file. If no default alias is found, then the local address is left as is.
An empty argument to the aliases command disables the replacement of local addresses. This is the default.

Obsolete; you can achieve the same and more using the substitution patterns of the from command.
Enable or disable automatic envelope-from addresses. The default is off. When enabled, an envelope-from address of the form user@domain will be generated. The local part will be set to USER or, if that fails, to LOGNAME or, if that fails, to the login name of the current user. The domain part can be set with the maildomain command. If the maildomain is empty, the envelope-from address will only consist of the user name and not have a domain part. When auto_from is disabled, the envelope-from address must be set explicitly.

Obsolete; you can achieve the same and more using the substitution patterns of the from command.
Set a domain part for the generation of an envelope-from address. This is only used when auto_from is on. The domain may be empty.

Examples

Configuration file

# Example for a user configuration file

/.msmtprc
#
# This file focusses on TLS and authentication. Features not used here include
# logging, timeouts, SOCKS proxies, TLS parameters, Delivery Status Notification
# (DSN) settings, and more.

# Set default values for all following accounts.
defaults

# Use the mail submission port 587 instead of the SMTP port 25.
port 587

# Always use TLS.
tls on

# Set a list of trusted CAs for TLS. The default is to use system settings, but
# you can select your own file.
#tls_trust_file /etc/ssl/certs/ca-certificates.crt

# A freemail service
account freemail

# Host name of the SMTP server
host smtp.freemail.example

# As an alternative to tls_trust_file, you can use tls_fingerprint
# to pin a single certificate. You have to update the fingerprint when the
# server certificate changes, but an attacker cannot trick you into accepting
# a fraudulent certificate. Get the fingerprint with
# $ msmtp —serverinfo —tls —tls-certcheck=off —host=smtp.freemail.example
#tls_fingerprint 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33

# Envelope-from address
from joe_smith@freemail.example

# Authentication. The password is given using one of five methods, see below.
auth on
user joe.smith

# Password method 1: Add the password to the system keyring, and let msmtp get
# it automatically. To set the keyring password using Gnome’s libsecret:
# $ secret-tool store —label=msmtp
# host smtp.freemail.example
# service smtp
# user joe.smith

# Password method 2: Store the password in an encrypted file, and tell msmtp
# which command to use to decrypt it. This is usually used with GnuPG, as in
# this example. Usually gpg-agent will ask once for the decryption password.
passwordeval gpg2 —no-tty -q -d

# Password method 3: Store the password directly in this file. Usually it is not
# a good idea to store passwords in cleartext files. If you do it anyway, at
# least make sure that this file can only be read by yourself.
#password secret123

# Password method 4: Store the password in

/.netrc. This method is probably not
# relevant anymore.

# Password method 5: Do not specify a password. Msmtp will then prompt you for
# it. This means you need to be able to type into a terminal when msmtp runs.

# A second mail address at the same freemail service
account freemail2 : freemail
from joey@freemail.example

# The SMTP server of your ISP
account isp
host mail.isp.example
from smithjoe@isp.example
auth on
user 12345

# Set a default account
account default : freemail

Using msmtp with Mutt

Create a configuration file for msmtp and add the following lines to your Mutt configuration file:
set sendmail=»/path/to/msmtp»
set use_from=yes
set realname=»Your Name»
set from=you@example.com
set envelope_from=yes
The envelope_from=yes option lets Mutt use the -f option of msmtp. Therefore msmtp chooses the first account that matches the from address you@example.com.
Alternatively, you can use the -a option:
set sendmail=»/path/to/msmtp -a my-account»
Or set everything from the command line (but note that you cannot set a password this way):
set sendmail=»/path/to/msmtp —host=mailhub -f me@example.com —tls —tls-trust-file=trust.crt»

If you have multiple mail accounts in your msmtp configuration file and let Mutt use the -f option to choose the right one, you can easily switch accounts in Mutt with the following Mutt configuration lines:
macro generic » 1″ «:set from=you@example.com»
macro generic » 2″ «:set from=you@your-employer.example»
macro generic » 3″ «:set from=you@some-other-provider.example»

Using msmtp with mail

Define a default account, and put the following in your

/.mailrc:
set sendmail=»/path/to/msmtp»

Using msmtp with Tor

Use the following settings:
proxy_host 127.0.0.1
proxy_port 9050
tls on
Use an IP address as proxy host name, so that msmtp does not leak a DNS query when resolving it.
TLS is required to prevent exit hosts from reading your SMTP session.
Do not set domain to something that you do not want to reveal (do not set it at all if possible).

Aliases file

# Example aliases file

# Send root to Joe and Jane
root: joe_smith@example.com, jane_chang@example.com

# Send cron to Mark
cron: mark_jones@example.com

# Send everything else to admin
default: admin@domain.example

Files

System configuration file. Use —version to find out what SYSCONFDIR is on your platform.

/.msmtprc or $XDG_CONFIG_HOME/msmtp/config

User configuration file.

/.netrc and SYSCONFDIR/netrc

The netrc file contains login information. Before prompting for a password, msmtp will search it in

/.netrc and SYSCONFDIR/netrc.

Environment

These variables override the user’s login name when constructing an envelope-from address. LOGNAME is only used if USER is unset.

Directory to create temporary files in. If this is unset, a system specific default directory is used.
A temporary file is only created when the -t/—read-recipients or —read-envelope-from option is used. The file is then used to buffer the headers of the mail (but not the body, so the file won’t get very large).

These environment variables are used only if neither —host nor —account is used and there is no default account defined in the configuration files. In this case, the host name is taken from SMTPSERVER, and the envelope from address is taken from EMAIL, unless overridden by —from or —read-envelope-from. Currently SMTPSERVER must contain a plain host name (no URL), and EMAIL must contain a plain address (no names or additional information).

Authors

msmtp was written by Martin Lambers .
Other authors are listed in the AUTHORS file in the source distribution.

See Also

sendmail(8), netrc(5) or ftp(1)

Источник

Browse free open source Email software and projects for Windows below. Use the toggles on the left to filter open source Email software by OS, license, language, programming language, and project status.

  • We create cultures where employees love to work, learn, connect &amp; succeed. Icon

    As a global leader in Social Employee Recognition, Madison delivers intuitive and multi-faceted Recognition, Incentive, and Service Anniversary programs powered by Maestro, our uniquely configurable cloud-based SaaS technology.

  • Open LMS leverages open-source software to deliver an effective and engaging learning experience. Icon

    As the largest commercial provider of hosting and support services for the open-source Moodle™ learning platform, we help organizations and institutions deliver great learning experiences without complexities

  • 1

    Scrollout F1

    • Designed for Linux and Windows email system administrators, Scrollout F1 is an easy to use, already adjusted email firewall (gateway) offering free anti-spam and anti-virus protection aiming to secure existing email servers, old or new, such as Microsoft Exchange, Lotus Domino, Postfix, Exim, Sendmail, Qmail and others.
    • Built-in multilayer security levels make configuration effort equal to a car radio.
    • It combines simplicity with effective protection using powerful open source with additional set of rules & filters.
    • Available as 64bit:
    — ISO image (Internet connection required during installation)
    — install from scratch (Internet connection required during installation).
    • Minimum Requirements (for 5,000 messages/day):
    1 GB of RAM
    30 GB storage drive
    1 Processor x86/AMD64
    1 Ethernet x 1 IPv4 address
    UDP ports: 53 123 4500 6277 24441
    TCP ports: 25 80 443 2703

    Leader badge

    Downloads:
    165,346 This Week

    Last Update:
    2018-04-08

    See Project

  • 2

    Anti-Spam SMTP Proxy Server

    The Anti-Spam SMTP Proxy (ASSP) Server project aims to create an open source platform-independent SMTP Proxy server which implements auto-whitelists, self learning Hidden-Markov-Model and/or Bayesian, Greylisting, DNSBL, DNSWL, URIBL, SPF, SRS, Backscatter, Virus scanning, attachment blocking, Senderbase and multiple other filter methods. Click ‘Files’ to download the professional version 2.6.7 build 22137.
    A linux(ubuntu 18.04 LTS) and a freeBSD 11.2 based ready to run OVA of ASSP V2 are also available for download.
    NOTICE:
    V1 development has been stopped at the end of 2014 (1.10.1 build 16060). Possibly there will be done some bugfixing in future.
    Please upgrade to V2, which is and will be actively maintained.

    Leader badge

    Downloads:
    82,194 This Week

    Last Update:
    2023-01-02

    See Project

  • 3

    SquirrelMail

    SquirrelMail

    SquirrelMail is a PHP-based Web email client. It includes built-in pure PHP support for IMAP and SMTP, and renders all pages in pure HTML 4.0 for maximum compatibility across browsers. It has strong MIME support and a flexible plugin system.

    Leader badge

    Downloads:
    4,694 This Week

    Last Update:
    2023-01-03

    See Project

  • 4

    theHarvester

    theHarvester is a very simple to use, yet powerful and effective tool designed to be used in the early stages of a penetration test or red team engagement. Use it for open source intelligence (OSINT) gathering to help determine a company’s external threat landscape on the internet. The tool gathers emails, names, subdomains, IPs and URLs using multiple public data sources.

    Downloads:
    141 This Week

    Last Update:
    2022-08-14

    See Project

  • Find and apply for a better job Icon

    Find the next step in your career. Find and apply for remote jobs and jobs in your area using the Slashdot Job Board. Browse by job, company, location, and more.

  • 5

    Mailspring

    Mailspring

    A faster, leaner email client and fork of Nylas Mail

    Mailspring is a fast and lean mail client that’s a new version of Nylas Mail. It’s maintained by one of Nylas Mail’s original authors, with plenty of great features and enhancements such as a new C++ sync engine that allows it to use 50% less RAM. Heavy dependencies have also been removed and the package manager rewritten for even greater speed.
    Written in TypeScript with Electron and React, it is cross-platform (macOS, Windows and Linux) and designed to be easy to extend.

    Downloads:
    98 This Week

    Last Update:
    2023-01-03

    See Project

  • 6

    Windows MBox Viewer

    Free Windows Mbox Viewer.
    Gain access to mbox archives or single eml messages.
    View attachments and export single mails in eml format.
    Access large box files such as Google Takeout or Mozilla Thunderbird Archives.
    Development of mbox viewer continues now at github: https://github.com/eneam/mboxviewer
    **NOTE**: Windows Defender may sometimes report incorrectly that mbox-viewer contains malware. Please report the case to the development. Development will ask Windows Security to update Windows Defender rules to resolve the issue. Last time the incorrect detection was corrected by Microsoft Security within few hours. User will need to run Windows Update to install the latest updated detection rules.

    Leader badge

    Downloads:
    2,346 This Week

    Last Update:
    2022-12-31

    See Project

  • 7

    MOSINT

    MOSINT

    An automated e-mail OSINT tool

    MOSINT is the fastest OSINT Tool for emails. It helps you gather information about the target email. Email validation, check social accounts, check data breaches and password leaks, finding related emails and domains, scan Pastebin Dumps. Google Search and DNS Lookup.

    Downloads:
    66 This Week

    Last Update:
    2023-01-22

    See Project

  • 8

    Blat - Windows Command Line SMTP Mailer

    Blat — Windows Command Line SMTP Mailer

    Blat — A Windows (32 & 64 bit) command line SMTP mailer. Use it to automatically eMail logs, the contents of a html FORM, or whatever else you need to send.

    Leader badge

    Downloads:
    1,300 This Week

    Last Update:
    2022-08-01

    See Project

  • 9

    PHPMailer

    PHPMailer

    The classic email sending library for PHP

    PHPMailer – A full-featured email creation and transfer class for PHP. Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings. SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports. Validates email addresses automatically. Many PHP developers need to send email from their code. The only PHP function that supports this directly is mail(). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments. Formatting email correctly is surprisingly difficult. There are myriad overlapping (and conflicting) standards, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you’ll find online that uses the mail() function directly is just plain wrong, if not unsafe!

    Downloads:
    59 This Week

    Last Update:
    2022-12-08

    See Project

  • Protect Your Online Privacy with ExpressVPN Icon

    The VPN that just works. #1 Trusted leader in VPN. Enjoy unrestricted access worldwide. 30-day money-back guarantee. ExpressVPN defeats content restrictions and censorship to deliver unlimited access to video, music, social media, and more, from anywhere in the world. ExpressVPN hides your IP address and encrypts your network data so no one can see what you’re doing. One click, and you’re protected. A single ExpressVPN subscription comes with easy-to-use apps for every device you own. Mac, Windows, Android, iOS, Linux, routers, and so much more.
    Defeat hackers and spies with best-in-class encryption and leakproofing. Access any content, no matter your location. Say goodbye to geo-blocks. Connect to any of our unlimited-bandwidth, ultra-fast VPN servers.

  • 10

    mailsend

    A program to send mail via SMTP from command line

    mailsend is a simple command line program to send mail via SMTP protocol. It can send a piece of alert mail from a program in a networked Windows machine. It’s feature-filled, cross-platform, free and open source, and does not use any config file.

    Downloads:
    49 This Week

    Last Update:
    2021-05-04

    See Project

  • 11

    Outlook CalDav Synchronizer

    Free Outlook Plugin, which synchronizes events, tasks and contacts between Outlook and Google, SOGo, Nextcloud, Horde or any other CalDAV or CardDAV server. Supported Outlook versions are 2019, 2016, 2013, 2010 and 2007.
    This project was initially developed as a master thesis project at the University of Applied Sciences Technikum Wien, Software Engineering Degree program. Outlook CalDav Synchronizer is Free and Open-Source Software (FOSS), still you can support the project by donating on Sourceforge or directly within the About dialog of our Plugin.
    Contact us for enterprise support at

    Contact

    Leader badge

    Downloads:
    870 This Week

    Last Update:
    16 minutes ago

    See Project

  • 12

    GO Contact Sync Mod

    Please install the latest version >4.0, because it uses the new Google People API. The Google Contacts API is now deprecated and is scheduled for sunset on June 15, 2021.
    GO Contact Sync Mod synchronizes your Microsoft Outlook contacts with your Google Mail address book, including pictures, categories and contact notes.
    It also syncs your Outlook Calendar Appointments on demand to Google Calendar. This Mod fork adds many enhancements and bug fixes to the obviously dead project ‘Go Contact Sync’.
    Minimum requirement for GO Contact Sync Mod is .NET 4.7.2 and Windows 7 (32 or 64 bit).

    Leader badge

    Downloads:
    790 This Week

    Last Update:
    2022-08-16

    See Project

  • 13

    E-MailRelay

    E-MailRelay is a simple SMTP proxy and relay MTA, written in C++, for Linux and Windows. As a proxy all messages can be passed through a user-defined program, such as a spam-filter, which can drop, readdress, or edit messages as they pass through.

    Leader badge

    Downloads:
    792 This Week

    Last Update:
    2023-01-15

    See Project

  • 14

    King Phisher

    King Phisher is an open source tool that can simulate real world phishing attacks. It has an easy-to-use, flexible architecture that allows for full control over both emails and server content. It is useful for running awareness campaigns and training, and can only be used for legal applications when the explicit permission of the targeted organization has been obtained.

    Downloads:
    31 This Week

    Last Update:
    2022-08-08

    See Project

  • 15

    DavMail POP/IMAP/SMTP/Caldav to Exchange

    DavMail POP/IMAP/SMTP/Caldav to Exchange

    Ever wanted to get rid of Outlook ? DavMail is a POP/IMAP/SMTP/Caldav/Carddav/LDAP gateway allowing users to use any mail client with Exchange and Office 365, even from the internet through Outlook Web Access on any platform, tested on MacOSX, Linux and Windows

    Leader badge

    Downloads:
    615 This Week

    Last Update:
    2023-01-11

    See Project

  • 16

    trixbox

    trixbox CE is an easy to install, VOIP phone system based on the Asterisk PBX. trixbox is designed for home or office use. trixbox CE includes CentOS linux, mysql, and all the tools needed to run a business quality phone system. (formerly asterisk@home)

    Leader badge

    Downloads:
    641 This Week

    Last Update:
    2013-06-18

    See Project

  • 17

    Elastix

    Elastix

    Unified Communications Server

    Elastix is a software-based PBX powered by 3CX and based on Debian. An open-standards solution, Elastix is an easy to install and manage UC system compatible with popular IP phones, gateways and SIP trunks.
    Elastix is complete with unified communications features such as integrated WebRTC video conferencing, chat, presence and softphones and smartphone clients for Windows, Mac, iOS and Android.

    Leader badge

    Downloads:
    594 This Week

    Last Update:
    2021-11-04

    See Project

  • 18

    PostfixAdmin

    PostfixAdmin

    PostfixAdmin is a Web Based Management tool created for Postfix. It is a PHP based application that handles Postfix Style Virtual Domains and Users that are stored in MySQL, PostgreSQL or SQLite

    Leader badge

    Downloads:
    446 This Week

    Last Update:
    2022-01-11

    See Project

  • 19

    MsgViewer

    MsgViewer

    MsgViewer is email-viewer utility for .msg e-mail messages, implemented in pure Java. MsgViewer works on Windows/Linux/Mac Platforms. Also provides a java api to read mail messges (msg files) programmatically.

    Leader badge

    Downloads:
    534 This Week

    Last Update:
    2016-05-01

    See Project

  • 20

    Tutanota

    Tutanota

    Open source email service with a strong focus on security and privacy

    Tutanota is an open source email client focused on security and privacy. It is built with end-to-end encryption and 2FA, so you can be assured of utmost email security.
    Tutanota is always encrypted, so whether you’re using their secure webmail client, mobile apps or desktop clients, you can be sure to communicate securely.

    Downloads:
    14 This Week

    Last Update:
    6 days ago

    See Project

  • 21

    phpList

    phpList

    Powerful Open Source Email Marketing app with analytics & segmentation

    phpList delivers Open Source email marketing, including analytics, list segmentation, content personalisaton and bounce processing. Extensive technical features and a secure and stable codebase are the result of over 17 years of continuous development.
    Used in 95 countries, available in 20+ languages, and used to send 25 billion email campaigns last year.
    Deploy it with your own SMTP server, or get a free hosted account at http://phplist.com.

    Leader badge

    Downloads:
    354 This Week

    Last Update:
    2023-01-31

    See Project

  • 22

    Roundcube Webmail

    Roundcube Webmail is a browser-based, multilingual IMAP client with an application-like user interface. Roundcube provides the full functionality you’d expect from an email client, including MIME support, address book, folder manipulation, message searching, and spell check. Roundcube is written in PHP and JavaScript.

    Leader badge

    Downloads:
    260 This Week

    Last Update:
    2015-12-26

    See Project

  • 23

    listmonk

    listmonk

    High performance, self-hosted, newsletter and mailing list manager

    Performance and features packed into a single binary. Manage millions of subscribers across many single and double opt-in lists with custom JSON attributes for each subscriber. Query and segment subscribers with SQL expressions. Use the super fast bulk importer (10k records per second) or use HTTP/JSON APIs or interact with the simple table schema to integrate external CRMs and subscriber databases. Visualize and compare campaign performance. Connect external visualization programs to the database easily with the simple table structure. Create powerful, dynamic e-mail templates with the Go templating language. Use template expressions, logic, and 100+ functions in subject lines and content. Write HTML e-mails in a WYSIWYG editor, Markdown, raw syntax-highlighted HTML, or just plain text. Highly configurable, multi-threaded, high-throughput multi-SMTP e-mail queues for super fast campaign delivery.

    Downloads:
    10 This Week

    Last Update:
    2022-11-27

    See Project

  • 24

    Outlook Mail Merge Attachment

    Outlook Mail Merge Attachment is a script which can be used to add an attachment to an mail merge in Microsoft Outlook.

    Leader badge

    Downloads:
    215 This Week

    Last Update:
    2014-05-02

    See Project

  • 25

    Mail-in-a-Box

    Mail-in-a-Box

    Take back control of your email with this mail server in a box

    Mail-in-a-Box helps individuals take back control of their email by defining a one-click, easy-to-deploy SMTP+everything else server, a mail server in a box. Mail-in-a-Box lets you become your own mail service provider in a few easy steps. It’s sort of like making your own gmail, but one you control from top to bottom. Technically, Mail-in-a-Box turns a fresh cloud computer into a working mail server. But you don’t need to be a technology expert to set it up. Our goals are to make deploying a good mail server easy, promote decentralization, innovation, and privacy on the web, have automated, auditable, and idempotent configuration, not make a totally unhackable, NSA-proof server, and not make something customizable by power users. Mail-in-a-Box turns a fresh Ubuntu 18.04 LTS 64-bit machine into a working mail server by installing and configuring various components. It is a one-click email appliance. There are no user-configurable setup options. It «just works.»

    Downloads:
    6 This Week

    Last Update:
    2022-10-30

    See Project

msmtp is a very simple and easy to use SMTP client with fairly complete sendmail compatibility.

Installation

Install the msmtp package. Additionally, install msmtp-mta, which creates a sendmail alias to msmtp.

Basic setup

Since msmtp version 1.8.6 you can place your user configuration either at ~/.msmtprc or $XDG_CONFIG_HOME/msmtp/config. The following is an example of a msmtp configuration (the file is based on the per-user example file located at /usr/share/doc/msmtp/msmtprc-user.example; the system configuration file belongs at /etc/msmtprc and its corresponding example file is located at /usr/share/doc/msmtp/msmtprc-system.example).

Tip: If using Gmail you will need to either:

  • Use OAuth, via #OAuth2 Setup.
  • If you use two factor authentication: create an app password.
~/.msmtprc
# Set default values for all following accounts.
defaults
auth           on
tls            on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile        ~/.msmtp.log

# Gmail
account        gmail
host           smtp.gmail.com
port           465
tls_starttls   off
from           username@gmail.com
user           username
password       plain-text-password

# A freemail service
account        freemail
host           smtp.freemail.example
from           joe_smith@freemail.example
...

# Set a default account
account default : gmail

Note: If you are using SSL/TLS and receive a «Server sent empty reply» error message, see #Server sent empty reply.

The user configuration file must be explicitly readable/writeable by its owner or msmtp will fail:

$ chmod 600 ~/.msmtprc

To avoid saving the password in plain text in the configuration file, use passwordeval to launch an external program, or see the #Password management section below. This example using Gnu PG is commonly used to perform decryption of a password:

echo -e "passwordn" | gpg --encrypt -o .msmtp-gmail.gpg # enter id (email...)

Warning: Most shells save command history(e.g. .bash_history .zhistory). To avoid this, use gpg with shell stdin: gpg --encrypt -o .msmtp-gmail.gpg -r <email> -. The ending dash is not a typo, rather it causes gpg to use stdin. After running that snippet of code, type in your password, press enter, and press Control-d so gpg can encrypt your password.

~/.msmtprc
passwordeval    "gpg --quiet --for-your-eyes-only --no-tty --decrypt ~/.msmtp-gmail.gpg"

OAuth2 Setup

OAuth2 can be used to securely authenticate msmtp when basic username/password authentication is unsupported by the site configuration or otherwise undesirable.

mailctl

msmtp alone lacks the ability to renew or authorize OAuth2 credentials. A comprehensive solution is using the mailctl utility which provides IMAP/SMTP clients with renewal capabilities and authorization of OAuth2 credentials.

To use mailctl, install mailctl-binAUR and configure msmtp to use it:

   # account at Google with oauth2 access                                    
   account YOUR_EMAIL_NAME@gmail.com
   from YOUR_EMAIL_NAME@gmail.com
   user YOUR_EMAIL_NAME@gmail.com
   auth oauthbearer
   passwordeval mailctl access YOUR_EMAIL_NAME@gmail.com
   host smtp.gmail.com
   port 587
   tls on
   tls_trust_file /etc/ssl/certs/ca-certificates.crt

Access token renewal happens automatically in the background transparent to the user.

oauth2token

Install oauth2tokenAUR and follow its README to configure the account. Run the oauth2create script to obtain and store credentials for each account.

Add auth oauthbearer and passwordeval oauth2get provider account, substituting provider and account with the values you used for oauth2create in your config.

Wrapper on oauth2.py

This is a scripted method, using the msmtp setting oauthbearer for authentication.

Once you have your Gmail API setup, you can implement the wrapper script oauth2token (that employs secret-tool(1)) or an adaptation of oauth2token (that employs pass).

An msmtp configuration would be adapted thus:

auth oauthbearer
...
passwordeval <call_to_wrapper_script>

If you comment out the last line, msmtp will request you for the token that oauth2.py provides you, which is normally valid for one hour.

OAuth2 hack

Note: This method may work, but uses outdated tools.

To use XOAUTH2 authentication with Gmail (see official information), you can install the msmtp-oauth2AUR package. The package does a small hack so that the plain authentication method will send the AUTH XOAUTH2 password instead of the AUTH PLAIN ..., effectively disabling plain authentication and enabling XOAUTH2. Your msmtp would be adapted as follows:

from your@gmail_login_email
tls on
tls_starttls on
tls_certcheck off
auth plain
user any_thing_here
passwordeval "get-gmail-token"

The get-gmail-token script can be found from the source files of the msmtp-oauth2 package. See more information on getmail link about how this works. And see Gmail API quickstart for instruction on registering a Gmail APP and authorizing it to access emails.

Using the mail command

To send mails using the mail command you must install the package s-nail, which also provides the mailx command. You will also need to provide a sendmail-compatible MTA, either by installing msmtp-mta (which symlinks sendmail to msmtp) or by editing /etc/mail.rc to set the sendmail path:

/etc/mail.rc
set mta=/usr/bin/msmtp

A .msmtprc file will need to be in the home of every user who wants to send mail or alternatively the system wide /etc/msmtprc can be used.

msmtp also understands aliases. Add the following line to the defaults section of msmtprc or your local configuration file:

/etc/msmtprc
aliases               /etc/aliases

and create an aliases file in /etc

/etc/aliases
# Example aliases file
     
# Send root to Joe and Jane
root: joe_smith@example.com, jane_chang@example.com
   
# Send everything else to admin
default: admin@domain.example

Test functionality

The account option (--account=,-a) tells which account to use as sender:

$ echo "hello there username." | msmtp -a default username@domain.com

Or, send both a subject and a body:

$ printf "Subject: Testnnhello there username." | msmtp -a default username@domain.com

Or, with the addresses in a file:

To: username@domain.com
From: username@gmail.com
Subject: A test

Hello there.
$ cat test.mail | msmtp -a default <username>@domain.com

Tip: You can use --read-envelope-from instead of -a default to automatically choose account by the From: field in a message you are going to send.

Cronie default email client

Tango-view-refresh-red.pngThis article or section is out of date.Tango-view-refresh-red.png

To make Cronie use msmtp rather than sendmail, make sure msmtp-mta is installed, or edit the cronie.service systemd unit:

/etc/systemd/system/cronie.service.d/msmtp.conf
[Service]
ExecStart=
ExecStart=/usr/bin/crond -n -m '/usr/bin/msmtp -t'

Then you must tell cronie or msmtp what your email address is, either by:

  1. Add to /etc/msmtprc:
    aliases /etc/aliases

    and create /etc/aliases:

    your_username: email@address.com

    — OR —.

  • Add a MAILTO line to the crontab:
    MAILTO=email@address.com

Password management

Passwords for msmtp can be stored in plaintext, encrypted files, or a keyring.

GNOME Keyring

Storing passwords in GNOME Keyring is supported natively in msmtp. Setup the keyring as described on the linked wiki page and install libsecret. Then, store a password by running:

secret-tool store --label=msmtp host smtp.your.domain service smtp user yourusername

msmtp should now find the password automatically.

GnuPG

The password directive may be omitted. In that case, if the account in question has auth set to a legitimate value other than off, invoking msmtp from an interactive shell will ask for the password before sending mail. msmtp will not prompt if it has been called by another type of application, such as Mutt. For such cases, the --passwordeval parameter
can be used to call an external keyring tool like GnuPG.

To do this, set up GnuPG, including gpg-agent to avoid having to enter the password every time. Then, create an encrypted password file for msmtp, as follows. Create a secure directory with 700 permissions located on a tmpfs to avoid writing the unencrypted password to the disk. In that directory create a plain text file with the mail account password. Then, encrypt the file with your private key:

$ gpg --default-recipient-self -e /path/to/plain/password

Remove the plain text file and move the encrypted file to the final location, e.g. ~/.mail/.msmtp-credentials.gpg. In ~/.msmtprc add:

~/.msmtprc
passwordeval  "gpg --quiet --for-your-eyes-only --no-tty --decrypt ~/.mail/.msmtp-credentials.gpg"

Normally this is sufficient for a GUI password prompt to appear when, for example, sending a message from Mutt. If gpg prompt for the passphrase cannot be issued, then start the gpg-agent before. A simple hack to start the agent is to execute a external command in your muttrc using the backtick `command` syntax. For example, you can put something like the following in your muttrc:

muttrc
set my_msmtp_pass=`gpg -d mypwfile.gpg`

Mutt will execute this when it starts, gpg-agent will cache your password, msmtp will be happy and you can send mail.

Note: If you do this, you will have to restart mutt after gpg-agent clears the password to start sending emails again.

An alternative is to place passwords in ~/.netrc, a file that can act as a common pool for msmtp, OfflineIMAP, and associated tools.

pass

You may store your credentials inside of the pass password manager.

If you are using your main password (which is customarily stored in the first line of your pass file) to login into your SMTP server, you can add the following to your .msmptrc:

~/.msmtprc
passwordeval   "pass your_email_password_entry | head -n1"

If you are using Gmail, and have set up an app password, the following configuration will suit you better.
Save your app password inside your pass password file, but with a msmtp: prefix:

your_email_password_entry
your_main_password

login: your_username
url: the_url_of_your_email
msmtp: your_msmtp_app_password

Then add the following to your .msmptrc:

~/.msmtprc
passwordeval   "pass your_email_password_entry | awk '/^msmtp:/ { print $2; }'"

In either case, trying to send an email with msmtp will trigger pass, which may ask you for your pass master password if you have not entered it recently.

Miscellaneous

Using msmtp offline

Although msmtp is great, it requires that you be online to use it. This is not ideal for people on laptops with intermittent connections to the Internet or dialup users. Several scripts have been written to remedy this fact, collectively called msmtpqueue.

The scripts are installed under /usr/share/doc/msmtp/msmtpqueue. You might want to copy the scripts to a convenient location on your computer, (/usr/local/bin is a good choice).

Finally, change your MUA to use msmtp-enqueue.sh instead of msmtp when sending e-mail. By default, queued messages will be stored in ~/.msmtpqueue. To change this location, change the QUEUEDIR=$HOME/.msmtpqueue line in the scripts (or delete the line, and export the QUEUEDIR variable in .bash_profile like so: export QUEUEDIR="$XDG_DATA_HOME/msmtpqueue").

When you want to send any mail that you have created and queued up run:

$ /usr/local/bin/msmtp-runqueue.sh

Adding /usr/local/bin to your PATH can save you some keystrokes if you are doing it manually. The README file that comes with the scripts has some handy information, reading it is recommended.

Vim syntax highlighting

The msmtp source distribution includes an msmtprc syntax-highlighting script for Vim, which is available at /usr/share/vim/vimfiles/syntax/msmtp.vim. The filetype is not detected automatically. The easiest way to enable it is by adding a modeline at the top or bottom of the file(s), i.e.:

# vim:filetype=msmtp

Send mail with PHP using msmtp

Look for sendmail_path option in your php.ini and edit like this:

sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"

Note that you can not use a user configuration file (ie: one under ~/) if you plan on using msmtp as a sendmail replacement with php or something similar.
In that case just create /etc/msmtprc, and remove your user configuration (or not if you plan on using it for something else). Also make sure it is readable by whatever you are using it with (php, django, etc…).

From the msmtp manual: Accounts defined in the user configuration file override accounts from the system configuration file. The user configuration file must have no more permissions than user read/write

So it is impossible to have a conf file under ~/ and have it still be readable by the php user.

To test it place this file in your php enabled server or using php-cli.

<?php
mail("your@email.com", "Test email from PHP", "msmtp as sendmail for PHP");
?>

php-fpm will fail to send mails and logs the warning: PHP Warning: mail(mail.log): failed to open stream unless you set the permissions of your /etc/msmtprc to user read/write (600).

Troubleshooting

Issues with TLS

If you see the following message:

msmtp: TLS certificate verification failed: the certificate hasn't got a known issuer

It probably means your tls_trust_file is not right.

Just follow the fine manual. It explains you how to find out the server certificate issuer of a given smtp server. Then you can explore the /usr/share/ca-certificates/ directory to find out if by any chance, the certificate you need is there. If not, you will have to get the certificate on your own. If you are using your own certificate, you can make msmtp trust it by adding the following to your ~/.msmtprc:

tls_fingerprint <SHA1 (recommended) or MD5 fingerprint of the certificate>

If you are trying to send mail through Gmail and are receiving this error, have a look at this thread or just use the second Gmail example above.

If you are completely desperate, but are 100% sure you are communicating with the right server, you can always temporarily disable the cert check:

$ msmtp --tls-certcheck off

If you see the following message:

msmtp: TLS handshake failed: the operation timed out

You may be affected by this bug. Recompile with --with-ssl=openssl (msmtp is compiled with GnuTLS by default).

Server sent empty reply

If you get a «server sent empty reply» error, this probably means the mail server does not support STARTTLS over port 587, but requires TLS over port 465.

To let msmtp use TLS over port 465, add the following line to ~/.msmtprc:

tls_starttls off

Zoho SMTP server

It can also happen on Zoho SMTP servers when the mail has no
blank line between mail headers and mail body (see Debian bug #917260). The solution to this is to add an extra space in between:

"test-headernntest-body"

Issues with GSSAPI

If you get the following error

GNU SASL: GSSAPI error in client while negotiating security context in gss_init_sec_context() in SASL library.  This is most likely due insufficient credentials or malicious interactions.

Try changing your auth setting to plain, instead of gssapi in your .msmtprc file [1]:

auth plain

Envelope not accepted

In the case of

msmtp: envelope from address mail@server not accepted by the server
msmtp: server message: 530 5.5.1 Authentication Required.
msmtp: could not send mail (account default from /etc/msmtprc)

Try enabling authentication with

auth on

or any other method.

Понравилась статья? Поделить с друзьями:
  • Msis7012 an error occurred while processing the request contact your administrator for details
  • Msiexec exe exited on with error code 1603
  • Msiexec error code 1619
  • Msiexec command i return code 1612 hp как исправить
  • Msiexec command i return code 1603 hp как исправить