• Uncategorized

About linux : send-mail-from-linux-terminal-in-one-line-closed

Question Detail

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.

Question Answer

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

Configure Postfix to Use Gmail SMTP on Ubuntu


or any other similar tutorial.

You can use an echo with a pipe to avoid prompts or confirmation.

echo "This is the body" | mail -s "This is the subject" [email protected]

echo "Subject: test" | /usr/sbin/sendmail [email protected]

This enables you to do it within one command line without having to echo a text file. This answer builds on top of @mti2935’s answer. So credit goes there.

For Ubuntu users: First You need to install mailutils

sudo apt-get install mailutils

Setup an email server, if you are using gmail or smtp. follow this link. then use this command to send email.

echo "this is a test mail" | mail -s "Subject of mail" [email protected]

In case you are using gmail and still you are getting some authentication error then you need to change setting of gmail:

Turn on Access for less secure apps from here

You can also use sendmail:

/usr/sbin/sendmail [email protected] < /file/to/send

You can install the mail package in Ubuntu with below command.

For Ubuntu -:

$ sudo apt-get install -y mailutils

For CentOs-:

$ sudo yum install -y mailx

Test Mail command-:

$ echo "Mail test" | mail -s "Subject" [email protected]

Sending Simple Mail:

$ mail -s "test message from centos" [email protected]
hello from centos linux command line

Ctrl+D to finish

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.