Linux sending email command line

9 mail/mailx command examples to send emails from command line on Linux

The mail command is an essential one that should be available on any linux server so that various services and other web applications can generate and transmit emails.

In a previous post on mail command we saw how the mail command can be used to send emails from the command line on your linux server.

In this tutorial we shall be using an enhanced version of the mail command. Its called mailx (or just mail when installed), and it can do many more things than what the older mail command from gnu mailutils package can do.

How does it work

The mail/mailx command needs a local smtp server (MTA) running in order to deliver the emails. THe route taken by the email is somewhat like this —

mail -> sendmail -> local MTA -> recipient MTA [Inbox]

The recipient MTA would be gmail’s smtp server if your recipient is someone at gmail.com for instance. For the local MTA, you need to install an smtp server like Postfix. A basic installation of Postfix with minimal configuration would work in most cases.

Install the mailx command

On Ubuntu/Debian based systems the mailx command is available from 2 different packages —

We shall be using the heirloom-mailx package because it has more features and options.
On CentOS/Fedora based systems, there is only one package named «mailx» which is the heirloom package.

To find out what mailx package is installed on your system, check the «man mailx» output and scroll down to the end and you should see some useful information.

# ubuntu/debian $ sudo apt-get install heirloom-mailx # fedora/centos $ sudo yum install mailx

Using the mailx command

Once installed, the mailx command can be directly referenced with the name mail, so you just type in that in the command line.

1. Simple mail

Run the following command, and then mailx would wait for you to enter the message of the email. You can hit enter for new lines. When done typing the message, press Ctrl+D and mailx would display EOT.

After than mailx automatically delivers the email to the destination.

$ mail -s "This is the subject" [email protected] Hi someone How are you I am fine Bye EOT

2. Take message from a file

The message body of the email can be taken from a file as well.

Читайте также:  What is linux alternatives

The message can also be piped using the echo command —

3. Multiple recipients

To send the mail to multiple recipients, specify all the emails separated by a comma

4. CC and BCC

The «-c» and «-b» options can be used to add CC and BCC addresses respectively.

5. Specify From name and address

To specify a «FROM» name and address, use the «-r» option. The name should be followed by the address wrapped in «<>«.

6. Specify «Reply-To» address

The reply to address is set with the internal option variable «replyto» using the «-S» option.

# replyto email $ echo "This is message" | mail -s "Testing replyto" -S replyto="[email protected]" [email protected] # replyto email with a name $ echo "This is message" | mail -s "Testing replyto" -S replyto="Mark[email protected]>" [email protected]

7. Attachments

Attachments can be added with the «-a» option.

$ echo "This is message body" | mail -s "This is Subject" -r "Harry[email protected]>" -a /path/to/file [email protected]

8. Use external SMTP server

This is an exclusive feature, that you get only with heirloom mailx and not bsd mailx, or the mail command from gnu mailutils or the mutt command.

The mailx command can use an external smtp server to use to relay the message forward. The syntax is a bit lengthy but makes sense.

$ echo "This is the message body and contains the message" | mailx -v -r "[email protected]" -s "This is the subject" -S smtp="mail.example.com:587" -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user="[email protected]" -S smtp-auth-password="abc123" -S ssl-verify=ignore [email protected]
$ echo "This is the message body and contains the message" | mailx -v \ > -r "[email protected]" \ > -s "This is the subject" \ > -S smtp="mail.example.com:587" \ > -S smtp-use-starttls \ > -S smtp-auth=login \ > -S smtp-auth-user="[email protected]" \ > -S smtp-auth-password="abc123" \ > -S ssl-verify=ignore \ > [email protected]

You can use the gmail smtp servers and send emails via your gmail account. That is so cool!
For gmail specifically you would need to enable less secure apps settings before you can send mail like that.

9. Verbose — watch smtp communication

When using external smtp servers, you can choose to watch the entire smtp communication that is done in the background. This is useful specially when testing or debugging smtp servers.

$ echo "This is the message body and contains the message from heirloom mailx" | mailx -v -s "This is the subject" -S smtp="smtp.gmail.com:587" -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user="[email protected]" -S smtp-auth-password="mypassword" -S ssl-verify=ignore [email protected] Resolving host smtp.gmail.com . . . done. Connecting to 74.125.68.109:587 . . . connected. 220 mx.google.com ESMTP je4sm32812877pbd.94 - gsmtp >>> EHLO enlightened 250-mx.google.com at your service, [122.163.43.21] 250-SIZE 35882577 250-8BITMIME 250-STARTTLS 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8 >>> STARTTLS 220 2.0.0 Ready to start TLS >>> EHLO enlightened 250-mx.google.com at your service, [122.163.43.21] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8 >>> AUTH LOGIN 334 VXNlcmU6 >>> YmnbWFpbC5jb20= 334 UGFzcmQ6 >>> KnJgzKg== 235 2.7.0 Accepted >>> MAIL FROM:[email protected]> 250 2.1.0 OK je4sm32812877pbd.94 - gsmtp >>> RCPT TO:[email protected]> 250 2.1.5 OK je4sm32812877pbd.94 - gsmtp >>> DATA 354 Go ahead je4sm32812877pbd.94 - gsmtp >>> . 250 2.0.0 OK 1417930703 je4sm32812877pbd.94 - gsmtp >>> QUIT 221 2.0.0 closing connection je4sm32812877pbd.94 - gsmtp

Troubleshooting

In case the mails are not being delivered properly you need to check a few things. The first thing to check is that an smtp server (mta) is running locally. The netstat command can tell that

$ sudo netstat -ltnp | grep 25 [sudo] password for enlightened: tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN 2541/master tcp6 0 0 . 25 . * LISTEN 2541/master

If an stmp server like Postfix is running and still mails are not going, then try re-configuring Postfix for example. On Ubuntu/Debian systems, this can be done with the dpkg-reconfigure command

$ sudo dpkg-reconfigure postfix

Then retry, the mail command and it should work. If it still doesn’t, try contacting your server provider.

Читайте также:  Одно и многопоточность linux

No mails from local systems

If you try to send mails from your local computer to a gmail address, your mail would most likely be rejected, so don’t try doing that.

This is because ordinary computers connected to internet address have an ip address that is not associated with any valid domain as such, and gmail strictly verifies such credentials before approving any mail to go through.

Notes and Resources

Apart from mailx, there are other tools like Swaks and smtp-cli that can be used to send mails from command line and support various features like specifying smtp servers and adding attachments and so on.

However the mailx command is available in the default repositories of most common distros, so can be installed easily. Further it maintains a syntax very similar to that of the mail command which makes it a drop in replacement for the older mail command.

The mailx command is even capable of reading mails from remote IMAP servers, but that is something we kept out of this post and would talk later. To learn more check the man page for the mailx command with «man mailx».

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

14 Comments

  1. mano June 27, 2018 at 4:04 pm might be worth pointing out that most of this won’t work on a lot of systems,
    illegal option — S
    illegal option — a
    illegal option — r

Источник

Отправка почты из командной строки Linux

Обновлено

Обновлено: 05.05.2022 Опубликовано: 31.03.2017

Читайте также:  Драйвер hp laserjet pro 400 m401dn linux

Подготовка

Для начала устанавливаем утилиту для отправки почты. В противном случае мы увидим ошибку mail: command not found. В Debian / Ubuntu:

Синтаксис

* в данном примере будет отправлено письмо на электронный адрес master@dmosk.ru с темой Test title и телом письма — Test text. Если при отправке возникли проблемы, можно проверить логи следующей командой:

Примеры использования командной строки для email-отправки

1. Отправка письма с вложением

echo ‘Attachment’ | mail -s ‘Subject attachment message’ -a /var/log/maillog -a /var/log/maillog2 master@dmosk.ru

echo ‘Attachment’ | mail -s ‘Subject attachment message’ -A /var/log/maillog -A /var/log/maillog2 master@dmosk.ru

* где /var/log/maillog и /var/log/maillog2 — файлы, которые будут прикреплены к письму. Обратите внимание, что обе команды отличаются по регистру опции a и A — все зависит от версии и сборки Linux (в каких-то нужно использовать маленькую, в каких-то — большую). Также обратите внимание, что в примере для Ubuntu мы отправим 2 файла — для этого просто добавляем к команде еще одну опцию прикрепления файла.

2. Несколько получателей

* в данном примере мы отправил письмо на ящики master@dmosk.ru и shmaster@dmosk.ru.

3. Отправка с копией

4. Указать отправителя

5. Отправка через другой SMTP сервер

echo «Test text» | mail -s «Test title» -a «Smtp: smtp.mail.ru:25» -a «From: postmaster@dmosk.ru» -a «Return-path: postmaster@dmosk.ru» master@dmosk.ru

Однако, если сторонний почтовый сервер работает по шифрованному каналу и требует аутентификацию, необходимо ввести следующее:

echo «Test text» | mail -v -s «Test title» -S smtp=»smtp.dmosk.ru:587″ -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user=»master@dmosk.ru» -S smtp-auth-password=»password» -S ssl-verify=ignore -S nss-config-dir=/etc/pki/nssdb -S from=postmaster@dmosk.ru master@dmosk.ru

* где smtp.dmosk.ru — сервер smtp; 587 — порт для подключения к серверу отправки; smtp-use-starttls указывает на использование шифрования через TLS; smtp-auth=login задает аутентификацию с использованием логина и пароля; smtp-auth-user и smtp-auth-password — соответственно логин и пароль; ssl-verify=ignore отключает проверку подлинности сертификата безопасности; nss-config-dir указывает на каталог с базами nss; from задает поле FROM

Mutt

При возникновении проблем, можно воспользоваться программой mutt. Сначала поставим ее. а) если используем CentOS / Red Hat:

Примеры использования Mutt

echo «Mail From» | mutt -s «subject» -e ‘my_hdr From: Дмитрий ‘ — master@dmosk.ru

* данной командой mutt отправит письмо от postmaster@dmosk.ru. 3. Отправка через другой сервер. Для начала, открываем файл с конфигурацией Mutt:

* в данном примере мы отправим всю нашу почту через узел smtp.mail.ru, порт 25. Или при необходимости авторизации на почтовом сервере:

set smtp_url=»smtp://smtp_user@smtp.mail.ru:465″
set smtp_pass = password
set ssl_verify_host = no
set ssl_verify_dates = no
set ssl_starttls = no
set ssl_force_tls = yes

  • smtp_user — имя учетной записи, под которой нужно авторизоваться на SMTP.
  • smtp_pass — пароль для аутентификации.
  • ssl_verify_host — нужно ли проверять валидность сертификата.
  • ssl_verify_dates — нужно ли проверять дату действия сертификата.
  • ssl_starttls — нужно ли использовать STARTTLS (обычно, при подключении по порту 587).
  • ssl_force_tls — нужно ли использование SSL/TLS (обычно, при подключении по порту 465).

Теперь можно отправлять письмо:

echo «Mail From» | mutt -s «subject» -e ‘my_hdr From: Дмитрий ‘ — master@dmosk.ru

Источник

Оцените статью
Adblock
detector