How to send email from the Linux command line Як відправити електронний з командного рядка Linux

by Sukrit Dhandhania on December 1, 2008 За Sukrit Dhandhania на 1 грудня 2008

Електронна поштаLinux

The Linux command line can be very powerful once you know how to use it. Linux командою рядка може бути дуже потужним, коли ви знаєте, як його використовувати. You can parse data, monitor processes, and do a lot of other useful and cool things using it. Ви можете аналізувати дані, відстежувати процеси, і зробити багато інших корисних речей і прохолодний його використання. There often comes a need to generate a report and mail it out. Там часто приходить до необхідності створення звіту і пошта його. It could be as simple a requirement as a notification that the day's backup went through fine, or did not. Це може бути як простим вимогою в повідомленні, що резервний день пройшов добре, чи ні. I'll help you get started with sending mails from the Linux command line and in shell scripts. Я допоможу вам почати роботу з відправкою пошти з командного рядка Linux і в сценаріях оболонки. We will also cover sending attachments from the command line. Ми будемо також покриття з відправленням вкладень з командного рядка. We will begin with the “mail” command. Ми почнемо з командою "пошту".

MAIL ПОШТА

First run a quick test to make sure the “sendmail” application is installed and working correctly. Перший запуск невеликий тест, щоб переконатися в "Sendmail" додаток встановлено і працює правильно. Execute the following command, replacing “you@youremailid.com” with your e-mail address. Виконайте наступну команду, замінивши "you@youremailid.com" на вашу електронну адресу.

# mail -s “Hello world” you@youremailid.com # Mail-S "Привіт всім" you@youremailid.com

Hit the return key and you will come to a new line. Хіт повернути ключ і ви потрапите на новий рядок. Enter the text “This is a test from my server”. Введіть текст "Це випробування з мого сервера". Follow up the text by hitting the return key again. Наступні тексту, натиснувши кнопку повторно повернути. Then hit the key combination of Control+D to continue. Потім натисніть комбінацію клавіш керування + D, щоб продовжити. The command prompt will ask you if you want to mark a copy of the mail to any other address, hit Control+D again. Командного рядка запитає вас, якщо ви хочете, щоб відзначити копія пошти на будь-який інший адресу, натисніть Ctrl + D знову. Check your mailbox. Перевірте Вашу поштову скриньку. This command will send out a mail to the email id mentioned with the subject, “Hello world”. Ця команда буде посилати пошту в електронний ідентифікатор згадується з тим, "Hello World".

To add content to the body of the mail while running the command you can use the following options. Щоб додати вміст в тілі листа після запуску команди ви можете використовувати наступні параметри. If you want to add text on your own: Якщо ви хочете додати текст на своєму власному:

# echo “This will go into the body of the mail.” | mail -s “Hello world” you@youremailid.com # Ехо "Це увійде в тексті листа." | Mail-S "Привіт всім" you@youremailid.com

And if you want mail to read the content from a file: І якщо ви хочете читати пошту з вмістом файла:

# mail -s “Hello world” you@youremailid.com < /home/calvin/application.log # Mail-S "Привіт всім" you@youremailid.com </ Головна / Calvin / application.log

Some other useful options in the mail command are: Деякі інші корисні опції поштою команди:

-s subject (The subject of the mail) -S суб'єкта (суб'єкт пошта)
-c email-address (Mark a copy to this “email-address”, or CC) -C Email-адреса (Mark копію цього "адреса електронної пошти", або СС)
-b email-address (Mark a blind carbon copy to this “email-address”, or BCC) B-Email-адреса (Mark сліпа копія цього "адреса електронної пошти", чи BCC)

Here's how you might use these options: Ось як ви можете використати такі опції:

# echo “Welcome to the world of Calvin n Hobbes” | mail -s “Hello world” calvin@cnh.com -c hobbes@cnh.com -b susie.derkins@cnh.com # Ехо "Ласкаво просимо у світ Гоббса Calvin N" | Mail-S "Привіт всім" calvin@cnh.com hobbes@cnh.com-C-B @ susie.derkins cnh.com

MUTT MUTT

One of major drawbacks of using the mail command is that it does not support the sending of attachments. Одним з основних недоліків використання поштового команди є те, що він не підтримує відправлення вкладень. mutt, on the other hand, does support it. Mutt, з іншого боку, робить її підтримки. I've found this feature particularly useful for scripts that generate non-textual reports or backups which are relatively small in size which I'd like to backup elsewhere. Я знайшов цю можливість особливо корисна для скриптів, які генерують нетекстові доповідей або резервних копій, що є відносно невеликий розмір, який я б хотів зробити резервну копію в іншому місці. Of course, mutt allows you to do a lot more than just send attachments. Звичайно, Матт дозволяє зробити набагато більше, ніж просто відправити вкладеннями. It is a much more complete command line mail client than the “mail” command. Це набагато більш повну командний рядок поштового клієнта, ніж команда "пошту". Right now we'll just explore the basic stuff we might need often. Зараз ми просто вивчити основні речі ми, можливо, буде потрібно часто. Here's how you would attach a file to a mail: От як би ви прикріпити файл до пошти:

# echo “Sending an attachment.” | mutt -a backup.zip -s “attachment” calvin@cnh.com # Ехо "Відправлення вкладення." | Mutt-backup.zip-S "вкладення" calvin@cnh.com

This command will send a mail to calvin@cnh.com with the subject (-s) “attachment”, the body text “Sending an attachment.”, containing the attachment (-a) backup.zip. Ця команда буде відправити лист calvin@cnh.com з предметом (-ів) "вкладення", текст "Надсилання вкладення.", Що містить вкладення (-а) backup.zip. Like with the mail command you can use the “-c” option to mark a copy to another mail id. Як і в пошті команди ви можете використовувати "-C", щоб відзначити опцію Копіювати в інший поштовий ідентифікатор.

SENDING MAIL FROM A SHELL SCRIPT Відправка повідомлень з Shell скриптів

Now, with the basics covered you can send mails from your shell scripts. Тепер, коли все саме можна відправляти пошту від ваших скриптів оболонки. Here's a simple shell script that gives you a reading of the usage of space on your partitions and mails the data to you. Ось простий скрипт, який дає вам читання використання простору на розділи і дані листа до вас.

#!/bin/bash #! / BIN / Bash
df -h | mail -s “disk space report” calvin@cnh.com DF-H | Mail-S "дискового простору доповіді" calvin@cnh.com

Save these lines in a file on your Linux server and run it. Збережіть ці рядки в файл на вашому сервері Linux і запустити його. You should receive a mail containing the results of the command. Ви повинні отримувати пошту, що містять результати команди. If, however, you need to send more data than just this you will need to write the data to a text file and enter it into the mail body while composing the mail. Однак, якщо вам потрібно відправити більше даних, чим саме вам потрібно, для запису даних у текстовий файл і ввести його в тіло листа при створенні пошти. Here's and example of a shell script that gets the disk usage as well as the memory usage, writes the data into a temporary file, and then enters it all into the body of the mail being sent out: Ось і приклад сценарію оболонки, яка отримує використання дискового простору, а також використання пам'яті, записує дані в тимчасовий файл, а потім надходить все це в тілі листа направляються на:

#!/bin/bash #! / BIN / Bash
df -h > /tmp/mail_report.log DF-H> / TMP / mail_report.log
free -m >> /tmp/mail_report.log безкоштовний-М>> / TMP / mail_report.log
mail -s “disk and RAM report” calvin@cnh.com < /tmp/mail_report.log Mail-S "диска і оперативної пам'яті доповіді" calvin@cnh.com </ TMP / mail_report.log

Now here's a more complicated problem. Тепер тут більш складна проблема. You have to take a backup of a few files and mail then out. Ви повинні прийняти резервного копіювання декількох файлів і пошти, то поза. First the directory to be mailed out is archived. Перший каталог для розіслані архівується. Then it is sent as an email attachment using mutt. Тоді він послав електронною поштою як вкладення допомогою Mutt. Here's a script to do just that: Ось скрипт, щоб зробити саме це:

#!/bin/bash #! / BIN / Bash
tar -zcf /tmp/backup.tar.gz /home/calvin/files Тар-zcf / TMP / backup.tar.gz / Home / Calvin / файли
echo | mutt -a /tmp/backup.tar.gz -s “daily backup of data” calvin@cnh.com ECHO | Mutt-A / TMP / backup.tar.gz-S "Щоденне резервне копіювання даних" calvin@cnh.com

The echo at the start of the last line adds a blank into the body of the mail being set out. Відлуння на початку останнього рядка додає пусте в тілі листа створюються Out.

This should get you started with sending mails form the Linux command line and from shell scripts. Це повинно вам розібратися з відправкою пошти форма рядка Linux команди і зі сценаріїв оболонки. Read up the “man page” for both mail and mutt for more options. Читайте вгору "Людина сторінка" для пошти і для Mutt більше варіантів.

Related Posts: Схожі повідомлення:
  • How to set up Evolution for email Як налаштувати еволюції для електронної пошти
  • How to post to Twitter from the Linux command line Як розмістити на Twitter з командного рядка Linux
  • Privacy Policy Політика конфіденційності
  • How to enable the root user account in Ubuntu Linux Як включити обліковий запис користувача root в Ubuntu Linux
  • Some useful Linux bash tricks Деякі корисні Bash Linux трюки
  • Get Simple Help tutorials just like this one in your email inbox every day - for free! Отримати довідки Прості підручників, як це у вашому поштовому ящику щодня - безкоштовно! Just enter your email address below: Просто введіть свою адресу електронної пошти нижче:

    You can always opt out of this email subscription at any time. Ви завжди можете відмовитися від підписки це повідомлення в будь-який час.

    { 9 comments… read them below or (9 коментарів ... читати їх нижче або add one Додати одну } )

    1 1 Michal Michal 12.08.08 at 3:20 am 12.08.08 о 3:20 ранку

    You may want to have a look at Ви можете подивитися на smtp-client.pl SMTP-client.pl . . Check out the usage examples. Ознайомтеся з прикладами вживання. I'd say it's the ultimate command line smtp client, but I'ma little biased Я кажу, що це кінцева командному рядку SMTP-клієнт, але Я трохи упереджено ;-)

    2 2 Matt 01.21.09 at 11:24 pm Метт 01.21.09 в 11:24 вечора

    echo | mutt -a -s /tmp/backup.tar.gz “daily backup of data” ECHO | Mutt-A-S / TMP / backup.tar.gz "Щоденне резервне копіювання даних" calvin@cnh.com calvin@cnh.com

    should be: повинно бути:

    echo | mutt -a /tmp/backup.tar.gz -s “daily backup of data” ECHO | Mutt-A / TMP / backup.tar.gz-S "Щоденне резервне копіювання даних" calvin@cnh.com calvin@cnh.com

    3 3 Ross McKillop Росс McKillop 01.22.09 at 12:47 am 01.22.09 в 12:47 ранку

    Matt – Matt --

    Thanks very much for catching that! Велике спасибі, що для лову! I've made the correction. Я зробила корекцію. Cheers! Ура!

    4 4 Jens Arnfelt 03.13.09 at 1:52 am Йенс Arnfelt 03.13.09 в 1:52 ранку

    Hi Привіт

    You can actually send binary attachment via “mail” the following way : Ви можете фактично відправити бінарного вкладення через "Пошта" наступним чином:

    uuencode /etc/hosts /etc/hosts | mail -s “mail with binary attachment” UUENCODE / ETC / хостів / ETC / хости | Mail-S "пошту з бінарними вкладення" me@mydomain.org me@mydomain.org

    BR BR
    Jens Arnfelt Йенс Arnfelt

    5 5 joviano 05.11.09 at 2:05 am joviano 05.11.09 в 2:05 ранку

    Basically have a test script, whose output comes by mail to me with the use of the command taken from this article: В основному мають тестовий скрипт, чия продукція постачається приблизно до мене з використанням команди взяті з цієї статті:

    echo `my test script` | mail -s “Test Result” Ехо "Мій тестовий скрипт` | пошта-S "Тест Результат" my_mail@mail.com my_mail@mail.com

    the problem here is that when i do this.. Проблема тут у тому, що, коли я роблю це .. it works correctly on the mailing front, however the mail that i then get ignores the line breaks in the output of the scripts. вона працює правильно, на передній розсилки, однак майже що я тоді отримати ігнорує рядків на виході з скриптів. I really need the line breaks for readability of the output results.. Мені справді потрібно строк для читання виводу результатів ..

    any pointers on how i could achieve this ?? будь-які рекомендації, як я міг би домогтися цього? .. .. would really like some help here дійсно хотіли б допомогти деяким тут

    6 6 martin 07.10.09 at 10:51 am Мартіна 07.10.09 в 10:51 ранку

    I'm looking for a program that will run from a script and will send mail via gmail smtp server. Я шукаю програму, яка буде запускати з сценарію і відправити пошту через SMTP-сервер Gmail. Any ideas? Будь-які ідеї?

    7 7 Michal Michal 07.10.09 at 4:54 pm 07.10.09 в 4:54 вечора

    martin: have a look at Martin: подивитися на smtp-client.pl SMTP-client.pl – it is designed to run from a script or a cron job and send email through a specified server. - Вона призначена для запуску з сценарію або завдання хрон і відправляти електронну пошту через вказаний сервер. For example: Наприклад:

    smtp-client.pl --server smtp.gmail.com --from someone@gmail.com --to some@body.else --subject Blah --attach /path/to/a/picture.png smtp-client.pl --server smtp.gmail.com --from someone@gmail.com --to some@body.else --subject Blah --attach /path/to/a/picture.png smtp-client.pl --server smtp.gmail.com --from someone@gmail.com --to some@body.else --subject Blah --attach /path/to/a/picture.png smtp-client.pl --server smtp.gmail.com --from someone@gmail.com --to some@body.else --subject Blah --attach /path/to/a/picture.png smtp-client.pl --server smtp.gmail.com --from someone@gmail.com --to some@body.else --subject Blah --attach /path/to/a/picture.png

    It can also authenticate with a Gmail username and password among other things. Він може також аутентифікацію з Gmail ім'я користувача і пароль між іншим.

    8 8 martin 07.22.09 at 1:50 pm Мартіна 07.22.09 о 1:50 вечора

    Thanks Michal. Завдяки Міхал. I'll check that out. Я перевірити це.

    9 9 Sujith John 08.01.09 at 7:33 am Sujith Джон 08.01.09 в 7:33 ранку

    An excellent tutorial !! Відмінний урок!! Thanks Much Thanks Much

    Leave a Comment Залишити коментар

    You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> Ви можете використовувати ці HTML теги і атрибути: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q Cite=""> <strike> <strong>