Linux mail to list

Содержание
  1. Отправка почты из командной строки Linux
  2. Подготовка
  3. Синтаксис
  4. Примеры использования командной строки для email-отправки
  5. 1. Отправка письма с вложением
  6. 2. Несколько получателей
  7. 3. Отправка с копией
  8. 4. Указать отправителя
  9. 5. Отправка через другой SMTP сервер
  10. Примеры использования Mutt
  11. linux-notes.org
  12. Установка утилиты mail в Unix/Linux
  13. Команды mail/mailx в примера на Unix/Linux
  14. 3 thoughts on “ Команды mail/mailx в примера на Unix/Linux ”
  15. Добавить комментарий Отменить ответ
  16. 5 Ways to Send Email From Linux Command Line
  17. 1. Using ‘sendmail’ Command
  18. 2. Using ‘mail’ Command
  19. 3. Using ‘mutt’ command
  20. 4. Using ‘SSMTP’ Command
  21. 5. Using ‘telnet’ Command
  22. 7 Best Linux Mailing List Managers
  23. Linux mail command examples – send mails from command line
  24. Send mails from command-line
  25. How the mail command works
  26. Install the mail command
  27. mail command examples
  28. 1. Sending a simple mail
  29. 2. Subject and Message in a single line
  30. 3. Take message from a file
  31. 4. Specify CC and BCC recipients
  32. 5. Sending to multiple recipients
  33. 6. Specify the FROM name and address
  34. 7. Send mail to a local system user
  35. 8. Verbose output
  36. Send mail with attachments using Mutt
  37. Send mail with bash/shell scripts
  38. Read mails
  39. Maildir-utils command
  40. Notes and Resources
  41. 26 thoughts on “ Linux mail command examples – send mails from command line ”

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

Подготовка

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

В Debian / Ubuntu:

apt-get install mailutils

В CentOS / Red Hat:

yum install mailx

Синтаксис

Можно отправить сообщение следующей командой:

echo «Test text» | mail -s «Test title» master@dmosk.ru

* в данном примере будет отправлено письмо на электронный адрес master@dmosk.ru с темой Test title и телом письма — Test text.

Если при отправке возникли проблемы, можно проверить логи следующей командой:

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

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

Для разных типов дистрибутива Linux команды могут отличаться.

а) для CentOS / Red Hat:

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

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. Несколько получателей

Для отправки письма нескольким получателям, просто перечисляем их через запятую:

echo «Test text» | mail -s «Test title» master@dmosk.ru,shmaster@dmosk.ru

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

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

Отправить копию на адрес master2@dmosk.ru:

echo «Test copy» | mail -s «Test copy title» master@dmosk.ru -c master2@dmosk.ru

Отправить скрытую копию на адрес master3@dmosk.ru:

echo «Test hidden copy» | mail -s «Test hidden copy title» master@dmosk.ru -b master3@dmosk.ru

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

В CentOS / Red Hat:

echo «Test text» | mail -s «Test title» -r postmaster@dmosk.ru master@dmosk.ru

В Debian / Ubuntu:

echo «Test text» | mail -s «Test title» master@dmosk.ru -aFrom:postmaster@dmosk.ru

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

а) Для Ubuntu / Debian:

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

б) Для CentOS / Red Hat:

echo «Test text» | mail -s «Test title» -S smtp=»smtp.mail.ru:25″ 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. Сначала поставим ее.

а) если используем CentOS / Red Hat:

yum install mutt

б) если используем Ubuntu / Debian:

apt-get install mutt

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

echo «Текст сообщения» | mutt -s «Тема» [дополнительные опции] —

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

1. Отправить вложение:

echo «Attachment» | mutt -s «subject» -a /var/log/maillog — master@dmosk.ru

* где /var/log/maillog — файл, который будет прикреплен к письму.

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

echo «Mail From» | mutt -s «subject» -e ‘my_hdr From: Дмитрий

* данной командой mutt отправит письмо от postmaster@dmosk.ru.

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

Для начала, открываем файл с конфигурацией Mutt:

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

Также можно добавить при необходимости:

set smtp_user = user
set smtp_pass = password
set ssl_verify_host = no
set ssl_verify_dates = no
set ssl_starttls = no
set ssl_force_tls = no

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

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

echo «Mail From» | mutt -s «subject» -e ‘my_hdr From: Дмитрий

Источник

linux-notes.org

Команды /Mail/mailx используемые в операционных систем UNIX/Linux для отправки электронной почты (так же, для полученные и чтения сообщений электронной почты) с возможностью удалять. В своей статье «Команды mail/mailx в примера на Unix/Linux» я расскажу как установить и использовать утилиту (команду) mail на ОС Unix или Linux.

Синтаксис команды mail:

Опции.

-v : Подробный режим. Детали отправки отображаются на экране.
-s : Опция задает тему для письма.
-c : Отправить СС (копии для других пользователей).
-b :Отправить BС (копии для других пользователей).
-f : Прочитать содержимое почтового ящика.
-e : Проверка на наличие почты в почтовом ящике.
-F : Записывает сообщение в файл с именем после получения.
-r : Опция для указания адреса отправителя в настройках отправки почты.
-u : Определяет сокращенния, аналог опции «mail -f /var/spool/mail/UserID».

Установка утилиты mail в Unix/Linux

Для того чтобы установить утилиту mail на CentOS/Fedora/RedHat, используйте:

Для того чтобы установить утилиту mail на Debian/Mint, используйте:

Теперь вы должны иметь команду mail, и можно приступать к работе.

Команды mail/mailx в примера на Unix/Linux

В своей статье «Команды mail/mailx в примера на Unix/Linux» я расскажу как пользоваться утилитой mail в ОС Unix/Linux. Приведу наглядные примеры использования данной утилиты.

Чтобы запустить программу «mail» и вывести список сообщений в почтовом ящике, выполните:

Команда mail показывает количество сообщений в ящике системы. Затем почтовая система отображает подсказку почтового ящика (?), ожидая ввода.

Читайте также:  Что такое atikmpag sys windows 10 как исправить

Когда вы видите эту строку, то нужно ввести субкоманду, чтобы увидеть список подкоманд, нужно нажать (?):

Данная команда (?) покажет все субкоманды для Mail.

Отправка электронной почты пользователю:

В команде «echo» задается некоторый текст для отправки по электронной почте.

Опция «-s» используется для указания темы для письма. Собственно, команда mail отправит емейл пользователю send_to_some@email.com. Можно обойтись и без команды echo, тогда команда будет выглядеть следующим образом:

В этом примере вы тогда, будите вводить в сообщении и чтобы остановить просто введите точку следующим образом (.):

Если вы хотите отправить письмо нескольким пользователям, то просто добавить емейл через пробел. Это будет выглядеть следующим образом:

Отправка содержимого текстового файла

3 thoughts on “ Команды mail/mailx в примера на Unix/Linux ”

Не подскажете, как настроить на свой почтовый адрес?

Установить и настроить свой почтовый сервер. Какой взять, — это на любителя. Я предпочитаю — postfix + dovecot. Настройку данной связки я опубликовывал тут: http://linux-notes.org/ustanovka-pochtovogo-servera-postfix-dovecot-i-squirrelmail-v-centos-redhat-fedora/

Если у меня все письма в первый экран не влазят, как увидеть следующую страницу списка?

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

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Источник

5 Ways to Send Email From Linux Command Line

We all know the importance of emails these days for information transfer. There are many free emails service providers which we used for use like Gmail, Yahoo, RediffMail etc, which provides a web interface for sending and receiving emails. But this is not enough, sometimes we also required to send emails from system command line. This tutorial will provide you multiple ways to send emails from the Linux command line. This is useful for sending email through our shell scripts, cronjobs etc.

There are various ways to send emails from the command line but here I am sharing few options used by most users. You can use anyone option given below to send email from Linux command line.

1. Using ‘sendmail’ Command

Sendmail is a most popular SMTP server used in most of Linux/Unix distribution. Sendmail allows sending email from command line. Use below instructions to send email using ‘sendmail‘ command.

Created a file with email content:

Subject: line will be used as subject for email.

Now send email using the following command.

2. Using ‘mail’ Command

mail command is most popular command to send emails from Linux terminal. Use few of below examples to send an email.

  • -s is used for defining subject for email.

Also, you can send an attachment with this command. Use -a for mailx and -A for mailutils.

  • Here -a is used for attachments. Use -A for debian based systems, which uses mailutils package.

Also, we can add comma separated emails to send the email to multiple recipients together.

3. Using ‘mutt’ command

Mutt is basically used for reading emails from Linux terminal from local user mailboxes, also useful to read emails from POP/IMAP servers. Mutt command is little similar to mail command. Use few of below examples to send an email.

Send an email including an attachment

4. Using ‘SSMTP’ Command

sSMTP allows users to send emails from SMTP server from Linux command line. For example to send an email to user [email protected] use following command. Now type your subject of the email as below with keyword Subject. After that type your message to be sent to the user, After finishing your message press CTRL+d (^d) to send the email.

5. Using ‘telnet’ Command

As per my experience, all system administrators use telnet command to test remote port connectivity test or login to the server remotely. Most of the newbie in Linux doesn’t know that we can send email using telnet also, which is the better way to troubleshoot email sending problems. Below is an example of email sending.

Red marked text is the user input and remaining is the responses of that commands.

Thank you for using this article. We will add more ways soon with this list. We also request you to help me with more commands which you know and not listed above.

Источник

7 Best Linux Mailing List Managers

An electronic mailing list offers the ability to efficiently distribute information to many internet users. It is similar in some ways to a traditional mailing list.

Electronic mailing lists are normally automated using dedicated mailing software and a reflector address. Mailing lists are often used as a two-way method of discussion between interested parties, or a one-way dissemination of information where only selected individuals can make posts.

Mailing lists provide a popular method of information exchange for both Linux developers and users. For example, the Linux kernel mailing list gets a high volume of traffic, acting as a focal point for sharing patches, discussing implementation details, reporting bugs, and new features. Many prominent companies participate in these discussions including Intel, IBM, Oracle, and VMware.

Mailing list software enables users to manage electronic mail discussion and e-newsletter lists. There is a good range of mature open source mailing list software available for the Linux platform.

Spammers unfortunately try to obtain the lists of subscribers to mailing lists. Good mailing list software seeks to thwart the spammers’ activities. Mailing lists can accept email from non-subscribers. To prevent spam being posted to subscribers, mailing list servers employ layers of spam blocking and filtering.

To provide an insight into the quality of software that is available, we have compiled a list of 6 valuable open source mailing list managers. All of these tools are released under a freely distributable license. Here’s our verdict.

Let’s explore the 7 mailing list managers at hand. For each application we have compiled its own portal page, a full description with an in-depth analysis of its features, together with links to relevant resources.

Источник

Linux mail command examples – send mails from command line

Send mails from command-line

Being able to send emails from command-line from a server is quite useful when you need to generate emails programatically from shell scripts or web applications for example.

This tutorial explains, how to use to the mail command on linux to send mails from the command-line using the mail command.

How the mail command works

For those who are curious about how exactly the mail command delivers the mails to the recipients, here is a little quick explanation.

The mail command invokes the standard sendmail binary (/usr/sbin/sendmail) which in turns connects to the local MTA to send the mail to its destination. The local MTA is a locally running smtp server that accepts mails on port 25.

Читайте также:  Максимально легкая windows 10

This means that an smtp server like Postfix should be running on the machine where you intend to use the mail command. If none is running you get the error message «send-mail: Cannot open mail:25».

Install the mail command

The mail command is available from many different packages. These packages are available in the default repositores of most of the popular linux distributions like debian, ubuntu, centos and fedora.

Here is the list of some of the common packages that provide the mail command.

1. gnu mailutils
2. heirloom-mailx
3. bsd-mailx

Each flavor has a different set of options and supported features. For example the mail/mailx command from the heirloom-mailx package is capable of using an external smtp server to send messages, while the other two can use only a local smtp server.

In this tutorial we shall be using the mail command from the mailutils package, which is available on most Debian and Ubuntu based systems.

Use the apt-get command to install it

Now you should have the mail command ready to work.

mail command examples

Here are some examples of how to use the mail command to send mails from the command line. These examples shall give you a basic idea of the various options and features supported by the mail command.

Note: If you are trying to send a test mail to some mail provider like gmail or outlook, then you would need to run these commands on a server with proper configuration. If you try to send mail from you local machine or desktop, then most spam filters would probably block it.

1. Sending a simple mail

Run the command below, to send an email to [email protected] The s option specifies the subject of the mail followed by the recipient email address.

The above command is not finished upon hitting Enter. Next you have to type in the message. When you’re done, hit ‘Ctrl-D’ at the beginning of a line

The shell asks for the ‘Cc’ (Carbon copy) field. Enter the CC address and press enter or press enter without anything to skip.

From the next line type in your message. Pressing enter would create a new line in the message. Once you are done entering the message, press . Once you do that, the mail command would dispatch the message for delivery and done.

2. Subject and Message in a single line

To specify the message body in just one line of command use the following style

3. Take message from a file

If the email message is in a file then we can use it directly to send the mail. This is useful when calling the mail command from shell scripts or other programs written in perl or php for example.

Or a quick one liner

4. Specify CC and BCC recipients

Other useful parameters in the mail command are:

Here’s and example of how you might use these options

5. Sending to multiple recipients

It is also possible to specify multiple recipients by joining them with a comma.

6. Specify the FROM name and address

The «-a» option allows to specify additional header information to attach with the message. It can be used to provide the «FROM» name and address. Here is a quick example

The a option basically adds additional headers. To specify the from name, use the following syntax.

Note that we have to escape the less/great arrows since they have special meaning for the shell prompt. When you are issuing the command from within some script, you would omit that.

7. Send mail to a local system user

To send mail to a local system user just use the username in place of the recipient address

You could also append «@hostname» to the username, where the hostname should be the hostname of the current system.

8. Verbose output

Sometimes when testing mail servers, you would want to check the SMTP commands being used by the mail command. Use the «-v» option for that

If the mail fails to deliver due to an improperly configured mail server for example, the smtp command log will show what has gone wrong.

Send mail with attachments using Mutt

The mail command could do some basic things till now, but moving forward, it lacks important features like sending attachments.

So we have to use another command line tool called mutt. Mutt is like an enhanced version of the mail command with a very similar syntax.

Debian / Ubuntu users can install mutt with the apt command.

Fedora / CentOS or Red Hat Enterprise Linux (RHEL) users:

Now you are ready to send mail with attachments with command line interface.

Send a simple mail

Send mail with attachment

Use the «a» option to specify the path of the file to attach

According to the syntax of mutt options, it is necessary to separate the files and the recipients with a double dash «—«. Also the «-a» option should be last one.

Send mail with bash/shell scripts

This example demonstrates how the output of a command can be used as the message in the email.
Here is an easy shell script that reports disc usage over mail.

Open a new file and add the lines above to that file, save it and run on your box. You will receive an email that contains «du -sh» output.

Read mails

This is not something interesting and you would not be doing this in a real life scenario. It is just being shown for the sake of it.

The mail command can be used to read mails. Just run it without an options and it would list all the mails in your inbox

Here’s a sample output

At the end is q question mark which is an interactive prompt waiting for your command. Simply enter the number of the email you want to read and hit enter. It would open up the mail then.

After you are done reading the email, enter ‘q’ and hit enter to come back. Enter z and hit enter to bring back the list of emails.

The mail command by default reads the emails from the directory «/var/mail/ «. So every user has a separate mail directory.

This way of storing and fetching mails is not very useful or practical in real life, where mail address consist of domain name along with username and a single server could be hosting emails for multiple domains.

Читайте также:  Dws windows 10 download

Maildir-utils command

‘mu’ is a set of command-line tools for Linux/Unix that enable you to quickly find the e-mails you are looking for.

Debian/Ubuntu users can use the apt-get command to install it

To search mails from william with subject report use the following command —

To check the current mail configurations use the info option.

Notes and Resources

The mail command is a very basic command to send mails. It should be present and properly configured on any linux server, so that mails are generated and delivered properly.

The mail command is mostly used when you are writing bash scripts to send emails from a server in an automated fashion. Besides this, the mail command is not very useful as an email solution.

If you need to setup a complete email system on your server with the ability to send and receive emails on your own domain then go ahead and install applications like postfix, dovecot.

If you are looking for a more powerful mailing program use commands like mailx, swaks etc. They have the necessary options to specify external smtp servers as well.

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] .

26 thoughts on “ Linux mail command examples – send mails from command line ”

Aha! Maybe I understand? This not ’email’, but mail meaning a message sent to someone who works in the same workplace, for example? If this is the case it’s of no use to me at home — unless of couse I wish to send messages to myself!

Your article is beautifully explained, but the mail I sent never showed up. I checked: I did it the way you said.

I have had success (sending) with alpine, though I can’t understand most of that program!

Really liking your website!

If you need any devops services please get in touch, we’d be
happy to help you out.

$ mail -s “This is the subject” [email protected]

cannot send message: Process exited with a non-zero status

why does this keep happening, I’ve tried like over 10 different walk-throughs on how to configure emails, and all of them have ended with this message

I’ve figured out how to fix it, and found that ssmtp may be interfering postfix
I’ve updated postfix and finally managed to send a message with end status 0, yet… it never arrived

I am unable to send mail using sendmail to a particular email address(Distribution list). Please help me.
Server details:- Linux 2.6.32-754.11.1.el6.x86_64 #1 SMP Tue Jan 22 17:25:23 EST 2019 x86_64 x86_64 x86_64 GNU/Linux

Part of Code:-
[email protected]
echo From: $FROM > $MAIL_FILE
echo Cc: $CC >> $MAIL_FILE
echo To: $TO >> $MAIL_FILE
echo Subject: “Notification: >> $MAIL_FILE


/usr/lib/sendmail -t

How to send an email to distribution list using mail?

Hi
Very nice article! try to mail all recipients from a text file “mail.list which look like that
[email protected] ,[email protected],[email protected],[email protected],[email protected] etc

and command:
M=”mail.list”
mail -s “monthly logs” “$M”

Excellent article I don’t think I’ve seen one that is a comprehensive as this. Using the mail command is something I find helpful for shell scripting output reports for certain processes etc…
I’ve made a similar guide here and also gave your article here a link and credit: http://realtechtalk.com/mail_command_line_examples_of_how_to_send_an_email_using_Linux_Unix_and_the_Bash_Shell_or_Scripting-2021-articles

hi
I need to mail the below information, How to capture and send mail. kindly help
mail -s |”GG Daily Status Report” [email protected]

GGSCI>info all
Manager Prgname Status Lag CHKPT
Extract EX_R01 Running 00:00:00 00 00:00:00

$ sudo apt install mutt

$ echo “This is mutt from universe” | mutt -s “This is mutts subject” [email protected]
Error sending message, child exited 127 (Exec error.).

This article is perfect
I get more benefits thanks a lot…

Hey..I’ve ran multiple comment into single line..using &&. then i got 2 line output.

pwd && ls -altr | grep *INTD437*

when try to send mail of 2 line output..pwd && ls -l | grep *INT* | mail -s “file output” [email protected]

I’m only getting 1st line output in the mail. Can you suggest on this.

Regarding BCC and CC addresses when sending from a single line. I was trying to use the syntax above to send to CC and BCC addresses, but all the addresses ended up being in the To: field of the email. After reading documentation for GNU Mailutils, I found that you need to specify options first and then the address list.

$ mail [option…] [address…]

Hopefully this helps someone out in the future.

Is there any command to directly connect to mail from terminal

Hail Silver Moon, great article. Thanks!

I would like to make an addendum regarding the last topic you have written about attaching a file using the “mutt” tool:
For the reason of the “mailx” program being part of the POSIX Standard to server as a MUA, then I believe that the use of it would be more viable than the “mutt”. In addition, the [mailx] tool is not difficult to use. For more details: https://access.redhat.com/solutions/104833

Your article was exactly what I was looking for – great practical advice and examples!

I found your article to be concise and VERY helpful, thanks! I was having troubles sending automated mail with a bash script from a cron job where I wanted a complex, all text, message. I am going to browse the rest of your site now to see what other nuggets of useful info you have!

Glad to hear that you found the post useful.
Thanks for the comment.

i am using ubuntu 14.04 LTS and apt get install mailutils is not working in my system…what shouldi do.

sudo apt-get install mailutils

yum install mail

really interesting article. keep up the good work on linux command line. and keep posting the findings here.

I am using Linux Mint 13 (fully updated) installed all the packages listed in the article. Followed the tutorial and the commands work (sorta) but mail is never sent and their is no hcg directory in var/spool/mail , only a locked file called root and when I try to read the mail messages the command “mail” just brings up system log files and displays them as messages. Strange. Nothing at as indicated should happen in the tutorial.

probably need to configure your mda and mta, but the above should work for sending emails

Источник

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