简体   繁体   中英

how to send a mail with a message in unix script

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.

echo 'Message body goes here' | mail -s 'subject line goes here' email@provider.com

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

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. Eg /usr/sbin/sendmail or /usr/lib/sendmail.

Update :
See also this question

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

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

事先定义mailcontent并按照以下方式执行:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM