Как послать email от линии команды Linux

[[by]] Sukrit Dhandhania на 1-ое декабря 2008

Email Linux

Линия команды Linux может быть очень мощна как только вы умеете как использовать ее. Вы можете parse данные, процессы монитора, и делаете множество других полезных и холодных вещей использующ его. Часто приходит потребность произвести рапорт и переслать его вне. Оно смогло быть как просто требование как извещение что подпорка дня пошла через штраф, или не сделало. Я помогу вам получить начатым с посылкой почт от линии команды Linux и в сценария заполнения. Мы также покроем посылку приложений от линии команды. Мы начнем с командой «почты».

ПОЧТА

Первый прогон быстро испытание, котор нужно make sure применение «sendmail» установлен и работать правильно. Исполните following команду, заменяя ть «you@youremailid.com» с вашим адресом и-мэйла.

# почта - мир» you@youremailid.com s «здравствуйте!

Ударьте возвращенный ключа и вы придете к новой линии. Впишите текст «, котор это будет испытание от моего сервера». Прослеживание текст путем ударять возвращенный ключа снова. После этого ударьте ключевую комбинацию Control+D продолжать. Запрос командй спросит вам если вы хотите маркировать экземпляр почты к любому другому адресу, то, удару Control+D опять. Проверите ваш почтовый ящик. Эта команда send out почта к идентификации email упомянутому с вопросом, «здравствуйте! мир».

Добавить содержание к телу почты пока бегущ команда вы можете использовать following варианты. Если вы хотите добавить текст на ваших:, то

# вторите «этому пойдет в тело почты.» | почта - мир» you@youremailid.com s «здравствуйте!

И если вы хотите почту прочитать содержание от архива:, то

# почта - мир» you@youremailid.com s «здравствуйте!

Некоторые другие полезные варианты в команде почты являются следующими:

- вопрос s (Вопрос почты)
- email address c (Марк экземпляр к этому «email address», или CC)
- email address b (Марк слепое копия через копирку к этому «email address», или BCC)

Здесь будет как вы могли использовать эти варианты:

# вторите «гостеприимсву к миру Кельвин n Hobbes» | почта - мир» calvin@cnh.com s «здравствуйте! - c hobbes@cnh.com - b susie.derkins@cnh.com

MUTT

Один из главных drawbacks использования команды почты что он не поддерживает посылку приложений. mutt, с другой стороны, поддерживает его. Я счесл эту характеристику определенно полезно для сценариев производят non-текстуальные рапорты или подпорки относительно малы в размере я хотел был бы к подпорке в другом месте. 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

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. Like with the mail command you can use the “-c” option to mark a copy to another mail id.

SENDING MAIL FROM A SHELL SCRIPT

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
df -h | mail -s “disk space report” calvin@cnh.com

Save these lines in a file on your Linux server and run it. 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
df -h > /tmp/mail_report.log
free -m >> /tmp/mail_report.log
mail -s “disk and RAM report” calvin@cnh.com

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. Here’s a script to do just that:

#!/bin/bash
tar -zcf /tmp/backup.tar.gz /home/calvin/files
echo | mutt -a /tmp/backup.tar.gz -s “daily backup of data” calvin@cnh.com

The echo at the start of the last line adds a blank into the body of the mail being set out.

This should get you started with sending mails form the Linux command line and from shell scripts. Read up the “man page” for both mail and mutt for more options.

Related Posts:
  • How to set up Evolution for email
  • Some useful Linux bash tricks
  • How to monitor your Linux machine with netstat
  • How to set the date on your Linux machine
  • Linux command line magic - find and replace
  • 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.


    Bookmark and Share

    { 3 comments… read them below or add one }

    1 Michal 12.08.08 at 3:20 am

    You may want to have a look at smtp-client.pl. Check out the usage examples. I’d say it’s the ultimate command line smtp client, but I’m a little biased ;-)

    2 Matt 01.21.09 at 11:24 pm

    echo | mutt -a -s /tmp/backup.tar.gz ?daily backup of data? calvin@cnh.com

    should be:

    echo | mutt -a /tmp/backup.tar.gz -s ?daily backup of data? calvin@cnh.com

    3 Ross McKillop 01.22.09 at 12:47 am

    Matt -

    Thanks very much for catching that! I’ve made the correction. Cheers!

    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>