- 4 способа отправки вложений к электронным письмам из командной строки Linux
- Требования
- 1. Использование команды mail
- 2. Использование команды mutt
- 3. Использование команды mailx
- 4. Использование команды mpack
- Отправка почты из командной строки Linux
- Подготовка
- Синтаксис
- Примеры использования командной строки для email-отправки
- 1. Отправка письма с вложением
- 2. Несколько получателей
- 3. Отправка с копией
- 4. Указать отправителя
- 5. Отправка через другой SMTP сервер
- Примеры использования Mutt
- 4 Ways to Send Email Attachment from Linux Command Line
- Requirement
- 1. Using mail Command
- 2. Using mutt Command
- 3. Using mailx Command
- 4. Using mpack Command
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- 5 Ways to Send Email From Linux Command Line
- 1. Using ‘sendmail’ Command
- 2. Using ‘mail’ Command
- 3. Using ‘mutt’ command
- 4. Using ‘SSMTP’ Command
- 5. Using ‘telnet’ Command
4 способа отправки вложений к электронным письмам из командной строки Linux
Оригинал: 4 Ways to Send Email Attachment from Linux Command Line
Автор: Aaron Kili
Дата публикации: 17 декабря 2016 года
Перевод: А. Кривошей
Дата перевода: ноябрь 2017 г.
Как только вы осваиваетесь с использованием терминала в Linux, вам хочется делать все, просто набирая команды, в том числе отправлять сообщения электронной почты, и одним из важных аспектов отправки электронной почты являются вложения.
Особенно для системных администраторов важно иметь возможность прикрепить файл резервной копии, файл журнала или отчет о работе системы, и отправить его на удаленную машину.
В этой статье мы узнаем, как отправить электронное письмо с вложением из терминала Linux. Важно отметить, что для Linux существует несколько простых почтовых клиентов командной строки, которые можно использовать для обработки электронных писем.
Требования
Для эффективного использования этого руководства у вас должна быть рабочая система электронной почты или настроен один из агентов передачи почты (MTA) для Linux. MTA — это приложение, отвечающее за отправку и получение электронной почты с одного хоста на другой.
Ниже приведены различные известные методы отправки электронной почты с вложением из терминала.
1. Использование команды mail
mail является частью пакета mailutils (в Debian) или mailx (в RedHat), и используется для обработки сообщений в командной строке.
Теперь пришло время отправить вложение электронной почты, используя команду mail .
В приведенной выше команде используются следующие флаги:
-s — указывает тему сообщения.
-A — помогает прикрепить файл.
Вы также можете отправить сохраненное сообщение из файла следующим образом:
2. Использование команды mutt
mutt — популярный легковесный почтовый клиент командной строки для Linux.
Если его нет в вашей системе, введите следующую команду:
Вы можете отправить электронное письмо с вложением, используя следующую команду mutt:
-s — указывает тему сообщения.
-a — идентифицирует вложение.
3. Использование команды mailx
mailx работает почти как mutt, и также является частью пакета mailutils (в Debian).
Теперь отправьте почту с вложением из командной строки с помощью команды mailx.
4. Использование команды mpack
mpack кодирует именованный файл в одном или нескольких сообщениях MIME и отправляет сообщение одному или нескольким получателям, или записывает его в именованный файл или набор файлов, или отправляет его в группы новостей.
Чтобы отправить сообщение с вложением, выполните приведенную ниже команду.
Ранее на нашем сайте были опубликованы следующие статьи, касающиеся программ электронной почты для консоли и отправки приложений с помощью таких программ. Возможно, вы найдете в этих статьях что-то полезное для себя.
- Прием и отправка почты из командной строки
- Список команд программы mail
- Отправка сообщений электронной почты из командной строки в Linux или OpenWRT
Источник
Отправка почты из командной строки 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: Дмитрий
Источник
4 Ways to Send Email Attachment from Linux Command Line
Once you get familiar to using the Linux terminal, you wish to do everything on your system by simply typing commands including sending emails and one of the important aspects of sending emails is attachments.
Especially for Sysadmins, can attach a backup file, log file/system operation report or any related information, and send it to a remote machine or workmate.
In this post, we will learn ways of sending an email with attachment from the Linux terminal. Importantly, there are several command line email clients for Linux that you can use to process emails with simple features.
Requirement
To effectively and reliably use this tutorial, you must have a working mail system or setup one of the mail transfer agents (MTA’s) for Linux on your system.
A MTA is an application responsible for sending and receiving emails from one host to another.
Below are the various, well known methods of sending email with attachment from the terminal.
1. Using mail Command
mail is part of the mailutils (On Debian) and mailx (On RedHat) package and it is used to process messages on the command line.
Now its time to send an email attachment using mail command a shown.
In the above command, the flag:
- -s – specifies the message subject.
- -A – helps to attach a file.
You can as well send an existing message from a file as follows:
2. Using mutt Command
mutt is a popular, lightweight command line email client for Linux.
If you do not have it on your system, type the command below to install it:
You can send an email with attachment using the mutt command below.
where the option:
- -s – indicates the message subject.
- -a – identifies the attachment(s).
3. Using mailx Command
mailx works more like the mutt command and it it also a part of mailutils (On Debian) package.
Now send the attachment mail from the command-line using mailx command.
4. Using mpack Command
mpack encodes the named file in one or more MIME messages and sends the message to one or more recipients, or writes it to a named file or set of files, or posts it to a set of newsgroups.
To send a message with attachment, run the command below.
That’s all! Do you have in mind any other methods of sending emails with attachment from the Linux terminal, that are not mentioned in the list above? Let us know in the comments.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
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.
Источник