Linux 如何在unix脚本中发送带有消息的邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20426077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:33:54  来源:igfitidea点击:

how to send a mail with a message in unix script

linuxemailunixksh

提问by Rahul sawant

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:

Unix 新手并学习它的谈话和操作。我正在用 .ksh 编写脚本,并且需要发送带有消息的邮件。目前在我的脚本中使用这个命令:

    mailx -s"File not found" [email protected]

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.

此命令帮助我拥有主题和收件人姓名。我的问题是我怎样才能写一条消息。因为每次我运行脚本时它都会暂停并要求我输入消息然后执行,我想预先包含消息,这样脚本就不会在中间暂停。

回答by user2839978

echo 'Message body goes here' | mail -s 'subject line goes here' [email protected]

回答by nos

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

由于 mailx 将正文作为 stdin 的输入,您可以将正文通过管道传递给它:

echo "Hello World" | mailx -s"File not found" [email protected]

Or use a here document

或者使用这里的文档

mailx -s"File not found" [email protected] << END_TEXT
Hello World 
END_TEXT

回答by Christian Aigner

Try this on the command line or inside a script:

在命令行或脚本中试试这个:

echo "This is the message." | mailx -s "Subject" [email protected]

You can use pre-defined messages from files:

您可以使用来自文件的预定义消息:

cat message.txt | mailx -s "Subject" [email protected]

回答by pitseeker

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

除了mailx(在其他答案中提到),您还可以使用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.

如果不在您的路径中,您可能需要将完整路径添加到 sendmail。例如 /usr/sbin/sendmail 或 /usr/lib/sendmail。

Update:
See also this question

更新
另见这个问题

回答by mahi_0707

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 protected]

EXAMPLE:

例子:

echo 'PFA report' | mailx -s 'Today's Report' -a `path`/report1306.txt  [email protected]

回答by Christine T.

Define the mailcontent beforehand and do it like this:

事先定义邮件内容并像这样执行:

mailx -s"File not found" [email protected] < mailcontent