Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

send mail from linux terminal in one line [closed]

Writer Sophia Terry

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

0

7 Answers

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 

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 or any other similar tutorial.

6

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

echo "This is the body" | mail -s "This is the subject" 
1
echo "Subject: test" | /usr/sbin/sendmail 

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.

1

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" 

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 < /file/to/send
1

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" 

Sending Simple Mail:

$ mail -s "test message from centos"
hello from centos linux command line

Ctrl+D to finish

1