Linux 使用 mail/mailx 發送郵件

在Linux伺服器維護的時候,發送郵件有時很有必要,當檢測到服務、程式有問題時,可以及時發送郵件通知您處理,當然可以自己寫個程式來發送,mailx已經很強大。

安裝前提確保關閉本機的sendmail服務或postfix服務
sendmail
# service sendmail stop
# chkconfig sendmail off
postfix
# service postfix stop
# chkconfig postfix off

安裝 mailx

# ubuntu/debian
$ sudo apt-get install heirloom-mailx

# fedora/centos
$ sudo yum install mailx

1. 簡單的郵件

$ mail -s "This is the subject" someone@example.com
Hi someone
How are you
I am fine
Bye
EOT

輸入第一行命令,回車之後就可以輸入郵件的內容了,完成輸入內容後按 CTRL+D ,mailx 就會顯示出 EOT。

2. 使用檔中的取郵件內容

$ mail -s "This is Subject" someone@example.com < /path/to/file

或者可以使用 echo

$ echo "This is message body" | mail -s "This is Subject" someone@example.com

3. 多個收件人

多個收件人,收件位址只需要用逗號“,”隔開即可。

$ echo "This is message body" | mail -s "This is Subject" someone@example.com,someone2@example.com

4. 抄送和密送CC,BCC

用 -c 表示抄送,-b 表示密送

$ echo "This is message body" | mail -s "This is Subject" -c ccuser@example.com someone@example.com

5. 定義寄件者資訊

使用 -r 定義寄件者

$ echo "This is message body" | mail -s "This is Subject" -r "Harry<harry@gmail.com>" someone@example.com

6. 使用特殊的回復位址

# 回復地址
$ echo "This is message" | mail -s "Testing replyto" -S replyto="mark@gmail.com" someone@example.com

# 回復地址和名稱
$ echo "This is message" | mail -s "Testing replyto" -S replyto="Mark<mark@gmail.com>" someone@example.com

7. 發送附件

使用 “-a” 加上檔路徑即可

$ echo "This is message body" | mail -s "This is Subject" -r "Harry<harry@gmail.com>" -a /path/to/file someone@example.com

8. 使用外部的SMTP伺服器

使用外部的SMTP伺服器,這樣就可以不用自己架設郵件伺服器了。

$ echo "This is the message body and contains the message" | mailx -v -r "someone@example.com" -s "This is the subject" -S smtp="mail.example.com:587" -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user="someone@example.com" -S smtp-auth-password="abc123" -S ssl-verify=ignore yourfriend@gmail.com

或者使用換行的形式,可讀性更強

$ echo "This is the message body and contains the message" | mailx -v \
> -r "someone@example.com" \
> -s "This is the subject" \
> -S smtp="mail.example.com:587" \
> -S smtp-use-starttls \
> -S smtp-auth=login \
> -S smtp-auth-user="someone@example.com" \
> -S smtp-auth-password="abc123" \
> -S ssl-verify=ignore \
> yourfriend@gmail.com

9. 配置外部的SMTP伺服器

vim /etc/mail.rc 在最後添加個能發送郵件的帳號

set smtp="mail.example.com:587"
set smtp-use-starttls
set smtp-auth=login
set smtp-auth-user="someone@example.com"
set smtp-auth-password="abc123"
set ssl-verify=ignore

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

Scroll to Top