how to send a mail with a message in unix script

2019-04-08 10:12发布

问题:

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.

回答1:

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


回答2:

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


回答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



回答4:

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


回答5:

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


回答6:

Define the mailcontent beforehand and do it like this:

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