使用unix shell脚本发送电子邮件

时间:2009-11-23 09:23:09

标签: bash email shell unix scripting

我必须编写一个脚本来使用unix shell脚本发送邮件。

以下脚本允许我拥有可变的邮件正文。

下面的代码中是否有可变主题部分?

#!/bin/bash
# Sending mail to remote user

sender="root@sped56.lss.emc.com"
receiver="root@sped56.lss.emc.com"
body="THIS IS THE BODY"
subj="THIS IS THE SUBJECT."


echo $body | mail $receiver -s "THIS IS THE SUBJECT" // this works fine
echo $body | mail $receiver -s $subj // ERROR - sends one mail with only
//"THIS" as subject and generates another error mail for the other three words 

4 个答案:

答案 0 :(得分:18)

你忘记了引号:

echo $body | mail $receiver -s "$subj"

请注意,您必须使用双引号(否则,不会展开变量)。

现在的问题是:为什么在$subj而不是$body$receiver附近引用双引号。答案是echo并不关心参数的数量。因此,如果$body扩展为多个单词,echo将只打印所有单词,其中只有一个空格。在这里,引号只有在你想保留双倍空格时才有意义。

对于$receiver,这是有效的,因为它只扩展为单个单词(无空格)。它会破坏John Doe <doe@none.com>等邮件地址。

答案 1 :(得分:3)

老问题,我知道,但可能很受欢迎。我最喜欢的方式提供了更大的灵活性,并且在我使用UNIX之后的任何UNIX / POSIX环境中都有用。只有sendmail路径可能会更改以满足本地实现。

sed <<"ENDMAIL" -e '/^From [^ ]/s/^From /From  /' -e 's/^\.$/. /' | /usr/sbin/sendmail -t -f "$sender"
To: $receiver, $receiver2, $receiver3
From: $sender
Subject: $subj
Any-Other-Standard-Optional-Headers: place headers in any order, including,
MIME-Version: 1.0
Content-Type: text/plain;
X-Mailer: any identity you want to give your E-mailing application
X-Your-Custom-Headers: X- headers can be your own private headers
x-Last-Header: a blank line MUST follow the last header

Your body text here

ENDMAIL
  • 在许多环境中,以“From ”开头,然后是非空格的行将被保留为消息包中的内部“开始新消息”标记。留出额外的空间以避免截断您的消息。 虽然在任何系统上使用perl替换sed的最大可移植性为:perl -p -e 's/^From ([^ ])/From $1/',因为某些UNIX系统中的sed并不是我喜欢的,特别是当echo "From me"通过管道输入本地sed时获得第三个空格。
  • 仅由句点组成的行是sendmail系列代理的经典消息结束标记。将这些行更改为在空格中结束...看起来相同但不再触发消息结束截断。
  • 您可以使用完整的电子邮件地址,例如:
    "Long Name" <email-addr@example.com>
  • 除了sendmail的-f选项之外,所有需要引号,转义等的文本都隐藏在“here here”中,这突然间不那么麻烦了。
  • 阅读此处使用的sendmail“ - ”选项的手册页。

更详细,您可以发送附件,不同的邮件编码,不同的电子邮件格式,多部分邮件等。对此进行一些研究,并注意信息不同部分所需的连字符数量。

Content-Type: multipart/mixed;
  boundary="----Some-unique-char-string-not-in-any-message"

------Some-unique-char-string-not-in-any-message
. . .

答案 2 :(得分:1)

您可以使用mailx并始终将引号括在变量

之内
mailx -s "$subj" my.email@my.domain.com < myfile.txt

答案 3 :(得分:0)

mailx不会出现在许多环境中。但你可以使用mail / sendmail

拥有相同的功能
cat myfile.txt | mail -s " Hi My mail goes here " mailid@domain.com 
相关问题