6

New to unix and learning the talk and walk of it. I am writing a script in .ksh and have a requirement of sending a mail with a message. Currently using this command in my script:

    mailx -s"File not found" abc@def.com

This command helps me having a subject and the recipient name. My question is how can I write a message along with it. Cause every time i run the script it pauses and asks me to enter the message and then executes, I want to pre-include the message so the script would not pause in between.

mahi_0707
  • 1,030
  • 9
  • 17
Rahul sawant
  • 415
  • 3
  • 6
  • 13

6 Answers6

8
echo 'Message body goes here' | mail -s 'subject line goes here' email@provider.com
user2839978
  • 341
  • 2
  • 6
5

Try this on the command line or inside a script:

echo "This is the message." | mailx -s "Subject" abc@def.com

You can use pre-defined messages from files:

cat message.txt | mailx -s "Subject" abc@def.com
  • The 1st one works for me, but when i receive my mail the message body has "" as trialing which doesn't get displayed in mail but when i receive it you get a preview on your taskbar right its there i can see it doesn't make a difference but was curious to know Thanks alot for the help – Rahul sawant Dec 06 '13 at 14:35
3

Alternatively to mailx (mentioned in the other answers) you can also use sendmail:

cat <<EOF | sendmail -t
To: recipients-mailaddress
From: your-mailaddress
Subject: the-subject
mailtext
blabla
.
EOF

Perhaps you need to add the full path to sendmail if it's not in your path. E.g. /usr/sbin/sendmail or /usr/lib/sendmail.

Update:
See also this question

Community
  • 1
  • 1
pitseeker
  • 2,535
  • 1
  • 27
  • 33
2

as mailx takes the body as input on stdin you can pipe the body to it:

echo "Hello World" | mailx -s"File not found" abc@def.com

Or use a here document

mailx -s"File not found" abc@def.com << END_TEXT
Hello World 
END_TEXT
nos
  • 223,662
  • 58
  • 417
  • 506
  • The second looks trendy, i tried it but doesn't work for me :( – Rahul sawant Dec 06 '13 at 14:36
  • For the 1st command i used the following: mail_person=abc@def.com echo "test"|mailx -s"test" $mail_person now this command does mail me the message but also adds it in /var/spool/mail in unix – Rahul sawant Dec 06 '13 at 14:51
1

Define the mailcontent beforehand and do it like this:

mailx -s"File not found" abc@def.com < mailcontent
0

If you also want to add attachment to the you want to send. Here you go:

echo 'Type Message body' | mailx -s 'Type subject' -a path/filename.txt email@provider.com

EXAMPLE:

echo 'PFA report' | mailx -s 'Today's Report' -a `path`/report1306.txt  xyz@gmail.com
mahi_0707
  • 1,030
  • 9
  • 17