How to send email from the Linux command line

by Sukrit Dhandhania on December 1, 2008

Email Linux

The Linux command line can be very powerful once you know how to use it. 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. 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. Execute the following command, replacing “you@youremailid.com” with your e-mail address.

# mail -s “Hello world” 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. The command prompt will ask you if you want to mark a copy of the mail to any other address, hit Control+D again. Check your mailbox. This command will send out a mail to the email id mentioned with the subject, “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

And if you want mail to read the content from a file:

# mail -s “Hello world” you@youremailid.com < /home/calvin/application.log

Some other useful options in the mail command are:

-s subject (The subject of the mail)
-c email-address (Mark a copy to this “email-address”, or CC)
-b email-address (Mark a blind carbon copy to this “email-address”, or 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

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

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

  • http://www.logix.cz/michal/devel/smtp/ Michal

    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 ;-)

  • Matt

    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

  • http://www.simplehelp.net Ross McKillop

    Matt -

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

  • Jens Arnfelt

    Hi

    You can actually send binary attachment via “mail” the following way :

    uuencode /etc/hosts /etc/hosts | mail -s “mail with binary attachment” me@mydomain.org

    BR
    Jens Arnfelt

  • joviano

    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” 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

  • martin

    I’m looking for a program that will run from a script and will send mail via gmail smtp server. Any ideas?

  • http://logix.cz/michal/devel/smtp Michal

    martin: have a look at 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

    It can also authenticate with a Gmail username and password among other things.

  • martin

    Thanks Michal. I’ll check that out.

  • Sujith John

    An excellent tutorial !! Thanks Much

  • Pingback: How to quickly add Contacts to your Address Book from Mail | TuxWire : The Linux Blog

  • Vasanth

    Thank You. i exactly needed this.

    Thank you :-)

  • John Britto.J

    Friends I tried the procedure what is given for sending mail through command line.
    I was able to type subject , the message and even cc. But when I checked in my account there was no mail received like this.

  • hendro

    how to get mail using command line, sent through proxy.

    thanks

  • hendro

    i am sorry, i made a mistake, my question is:
    how to SEND mail using command line, sent through proxy.

    thanks

  • Erik

    Is there a way to use variables for the body of a message like in Mailx instead of reading from a file?

  • http://www.robinmitra.com Robin

    Thanks for the nice tutorial..
    @John Britto: I had the same problem on my Debian – was getting no email whatsoever. I had to install sendmail. After installing sendmail, it just started working!

  • Keisial

    Joviano, instead of
    echo `my test script` | mail -s “Test Result” my_mail@mail.com
    simply do
    my test script | mail -s “Test Result” my_mail@mail.com

    Equally, the df + free reports can also be done as:
    ( df -h; free -m ) | mail -s “disk and RAM report” calvin@cnh.com

  • Daniel

    well done and thanks. How would you add a carraige return to it. I tiried \n and \r\n and had no luck

  • Keisial

    You can simply do:
    echo -e “Hello\nWorld” | mail your@email

    However, not all systems support -e option on echo so it’s more portable to use:
    printf “Hello\nWorld” | mail your@email

  • Nige

    Hey There

    Been working on this all day (im a big linux noob) and finally got a solution that lets me set the “from” part, with line breaks, all piped into one line. Im going to use this with the exec command from within php to spawn off emails but not loose application speed (hopefully)

    printf “This is the main body of the mail\n with line break” | mail -s “Subject of the Email” to_user@example.com -f from_user@example.com

    hope this help someone else

  • Nige

    just to add to previous comment

    exec(“printf \”This is the main body of the mail\n with line break\” | mail -s \”Subject of the Email\” to_user@example.com -f from_user@example.com > /dev/null 2>&1 &”);

    will tell php to spawn off a separate thread so as not to hold up the scripts execution time.

  • http://caspian.dotconf.net/menu/Software/SendEmail/ Joseph

    Here’s a good solution: SendEmail
    An Email Program for Sending SMTP Mail from a Command Line

    It’s a single perl script, and it doesn’t make any [bad] assumptions such as sendmail running and configured properly. It supports attachments.

  • deepak

    how to send mials in linux

  • Pingback: how to set up sending mail from the command line

  • http://blog.littlebearz.com littlebearz

    Wow, thanks, this is quite useful, well indented.

  • Murray Crane

    All of you that had to install sendmail (or postfix, or any of the other bloated MTAs), if all you want is to get emails out of a machine and on to a mail smart host, take a look at ssmtp (it’s in APT with that name if you are a Debian/Ubuntu user). It’s one and only function is to “forward” the mails it receives to a mail smart host.

  • Tony

    Need to send with Cc: and the -c does not work, please refer to below:
    Trying: mail -s subject-blah inbox@abc.com -c inbox2@abc.com < my_body_file.txt

  • Pingback: Send webmail from CommandLIne

  • Kogychan

    thanks… perfect tutorial, exactly what I was looking for. BSBS (Be smart, Be Simple :) )

  • Pingback: Bmon, mail & other Linux goodies

  • Pingback: : Mike Mindel: How to send email from the Linux command line – Simple Help | MiloRiano: Computers news, tips, guides...

  • Pingback: Delicious Bookmarks for July 2nd through July 3rd « Lâmôlabs

  • queenet

    18 Nov 2008 – Whenever I go to my email I have a 100 junk emails – I signed up for website builders that were only scam forwarders. I tried emailing the senders, but they use fake accounts so I can never get rid of i

  • Ron

    very interesting and important + a very good tutorial

  • Pingback: Cron Job Nightly Email Question

  • Pingback: cron job

  • http://www.quehago.co Juan

    Thanks finally could test if my SMTP was installed correctly… now to connect it to the rails app…. ( :D )

  • tosiara

    I was getting “No recipients specified.” when trying your examples. Then I looked into man:

    -a [...] — attach file(s) to the message
    the list of files must be terminated with the “–” sequence

    You missed “–” after filename in your exampl

  • Carlos

    I have a problem: I can’t visualise the mail content in webmail or thunderbird when I send a mail with a script from a cron schedule:
    mail -s “avisobckmensual” user@xxxxx.com

    I receive the mail but instead of having content, I receive an empty mail with an attachment named “subjet”.octet-stream

    BUT, if I run the script directly from the terminal… it works flawlessly.

    Can you help me?

  • Raghav

    Hi All,

    i want to add from field to mail command…can any1 help me……..?

  • http://google rebelk iran

    hi chintu how are you i hope sam with you same

  • Pingback: Send email from command line « The Ubuntu Incident

  • Abhi

    hi, I am unable to receive mails….can some one tell me what is the reason???
    i installed mutt, ssmtp as well but no luck….

  • Toddb

    none of these commands work,  there must be more to it that a simple command

  • Rajeev Sharma

    None of the above commands are working.. :(

  • http://www.simplehelp.net/ Ross McKillop

    @fd18635dd98030e12d472dfd452aa4e7:disqus – which Linux/Unix/BSD etc are you running?

  • ukcjmad

    According to other websites you can send attachments using “mail” if you pipe the attachment through uuencode into the mail command line. Examples:

    uuencode surfing.jpeg surfing.jpeg | mail sylvia@home.com
    (cat mailtext; uuencode surfing.jpeg surfing.jpeg) | mail sylvia@home.com

  • Pingback: Les commandes Linux qui vous feront gagner du temps

  • malini

    none of these working

  • Naresh

    Awesome………………thanks

  • Saikat

    Malini can you please post your problem.

  • http://www.facebook.com/hans.stam Hans Stam

    You sir, are awesome

  • Isamaer

    the -a attachment on Mutt may need to go after the recipient not before.

  • Pingback: Sending mail from command line.

  • Pingback: Mémo commandes Linux ( 2 ) | Mémos RT

  • jayanth

    Hi, i am facing one problem i have written one script for disk space usagi shown the script below.

    a=`df -h /home/jayantc | tail -1 | cut -b40,41,42`

    if test $a -ge 60

    then

    echo “Hi jayanth You have used $a% of diskspace please delete some files from your Home directory to avoid space issue” | mutt -s “Disk_SPace details” jayanth-c@hcl.com

    else

    echo “You used less than 60% No problem” | mutt -s “Disk_SPace details” jayanth-c@hcl.com

    fi

    script will execute successfully but mails are not triggereing please help me out on this if i made any mistake.

  • Kimble

    What is the largest file you can attach and send using mutt?

  • Andrea

    thanks 1k

  • Pingback: Sending mail from shell console | Computing

  • Pingback: Sending mail from command line or shell program | Computing

  • George Brooke

    i get this when not doing from shell and just sending plain mail. what is goin on?

  • http://sergiofrancisco.com/ Sergio Francisco

    Very useful! Thanks.

  • Daniel

    He doesn’t have mutt or senmail installed…

  • ashish

    Helped me. cheers..!

  • James

    hello,

    how to tweak the mail command, so that it only emails if the log file is not empty.

  • Pingback: How do I send email from the linux command line? | MarkJacobsen.net

  • Sai

    awesome

  • Pingback: How to send log files to a particular e-mail address?

  • Jon

    you’d need to wrap it in a if statement, I doubt this could be done just with mail. Something like:
    if [ `du /path/to/log.log` -gt 0 ]
    then
    mail -s “file de log” < /path/to/log.log
    fi

  • Frank Lister

    using mail
    #!/bin/bash
    mail -s “My Subjet” myEmail@yahoo.com < /home/tmp/body.txt

    sometimes I get an email and sometimes I don't. Sometimes they appear fast in the inbox, sometimes it takes minutes/hours. Usually, the first email sent (of the day) goes fast, the others, who knows??

    cant the "mail" service be restarted? or anyone have an idea as to why/how this happens???

  • okau

    How to do NTLM authentication

  • Adhip

    thanks