簡體   English   中英

使用unix shell腳本發送電子郵件

[英]Sending email using unix shell 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 

你忘記了引號:

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

請注意,必須使用雙引號(否則,不會展開變量)。

現在的問題是:為什么在$subj周圍$subj雙引號而不是$body$receiver 答案是echo不關心參數的數量。 因此,如果$body擴展為多個單詞, echo將打印所有這些單詞之間的單個空格。 在這里,引號只有在你想要保留雙倍空格時才有意義。

至於$receiver ,這是有效的,因為它只擴展為一個單詞(沒有空格)。 對於像John Doe <doe@none.com>這樣的郵件地址,它會中斷。

老問題,我知道,但可能很受歡迎。 我最喜歡的方式提供了更大的靈活性,並且在我使用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/' as sed在某些UNIX系統中並不是我真正喜歡的,特別是如果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
. . .

你可以使用mailx並始終在變量周圍加上引號

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

mailx不會出現在許多環境中。 但您可以使用mail / sendmail獲得相同的功能

cat myfile.txt | mail -s " Hi My mail goes here " mailid@domain.com 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM