send mail from linux terminal in one line

cHam picture cHam · Dec 2, 2013 · Viewed 383.9k times · Source

I know there is the command mail in linux to send emails via command line. How can I send an simple email with one line from the terminal though?

For example:

mail [email protected] [subject] [body]

And have the email sent without any confirmation or prompts to the user?

The reason is, I want to send a brief message via email to myself when a specific event happens in a java program. The idea is that I will use Runtime.getRuntime()… etc. to send the mail command from my java program.

I used cron to do something similar in the past, but the current implementation doesn't use cron, so I need to try this out instead.

Answer

PSkocik picture PSkocik · Dec 2, 2013

mail can represent quite a couple of programs on a linux system. What you want behind it is either sendmail or postfix. I recommend the latter.

You can install it via your favorite package manager. Then you have to configure it, and once you have done that, you can send email like this:

 echo "My message" | mail -s subject [email protected]

See the manual for more information.

As far as configuring postfix goes, there's plenty of articles on the internet on how to do it. Unless you're on a public server with a registered domain, you generally want to forward the email to a SMTP server that you can send email from.

For gmail, for example, follow http://rtcamp.com/tutorials/linux/ubuntu-postfix-gmail-smtp/ or any other similar tutorial.