mail(或 mailx、mailutils)是 Linux 系統自帶的郵件客戶端,雖然界面樸素,但在腳本自動化告警、日誌報表投遞、批量通知等場景中極其實用。本文系統講解發送、附件、抄送、自定義發件人/回覆地址、管道輸入、郵箱查看與管理的完整用法。
# CentOS/RHEL
yum install -y mailx # 提供 mail 命令,後端通常用 postfix
# Ubuntu/Debian
apt-get install -y mailutils # 提供 mail 命令,後端可選 postfix/exim4
# 確保 MTA 運行
systemctl enable --now postfix
# 或 sendmail/exim4
| 參數 | 說明 | 示例 |
|---|---|---|
-s "Subject" | 郵件主題(含空格需引號) | -s "Daily Report" |
-r "addr" | 自定義發件人地址 (Envelope From) | -r "noreply@company.com" |
-R "addr" | 自定義回覆地址 (Reply-To) | -R "support@company.com" |
-c "addr" | 抄送 (CC) | -c "boss@company.com" |
-b "addr" | 密送 (BCC) | -b "audit@company.com" |
-a "file" | 添加附件 (mailx/Heirloom mailx) | -a /var/log/app.log |
-A "account" | 使用 ~/.mailrc 定義的賬戶 | -A gmail |
-f [file] | 讀取指定 mbox 文件 | -f /var/spool/mail/root |
-u user | 讀取指定用戶郵箱 | -u root |
mail -s "Server Alert" admin@example.com
# 回車後輸入正文,多行結束按 Ctrl+D
Disk usage on /data: 92%
Please check immediately.
EOT
echo "Backup completed at $(date)" | mail -s "Backup Status" admin@example.com
# 多行正文
cat <<EOF | mail -s "Report" admin@example.com
Server: $(hostname)
Time: $(date)
Status: OK
EOF
mail -s "Log Extract" admin@example.com < /var/log/app.log
mail -s "Report" -a /tmp/report.pdf admin@example.com < /dev/null
# < /dev/null 避免等待標準輸入
mail -s "Meeting" \
-r "system@company.com" \
-R "noreply@company.com" \
-c "manager@company.com" \
-b "archive@company.com" \
user1@example.com user2@example.com < /dev/null
#!/bin/bash
# batch-mail.sh
RECIPIENTS="user1@example.com user2@example.com user3@example.com"
SUBJECT="System Maintenance Notice"
BODY_FILE="/tmp/notice.txt"
for rcpt in $RECIPIENTS; do
mail -s "$SUBJECT" -r "noreply@company.com" "$rcpt" < "$BODY_FILE"
sleep 1 # 避免觸發郵件伺服器限流
done
mail # 進入交互模式,列出郵件列表
# 輸入數字查看對應郵件
# 輸入 h 顯示列表,d 刪除,u 恢復,s 保存到文件, q 退出保存, x 退出不保存
交互命令速查:
| 命令 | 功能 |
|---|---|
t [num] / type [num] | 顯示郵件內容 |
n / next | 顯示下一封 |
h / headers | 顯示郵件列表 |
d [num] / delete | 標記刪除 |
u [num] / undelete | 取消刪除標記 |
s [num] file / save | 保存郵件正文到文件(不含頭部) |
w [num] file / write | 保存純正文(含附件解碼) |
m addr / mail | 寫新郵件 |
r [num] / reply | 回覆發件人 |
R [num] / Reply | 回覆發件人及所有收件人 |
q / quit | 退出並應用刪除/保存 |
x / xit | 退出不應用變更 |
! | 執行 Shell 命令 |
# ~/.mailrc
set from="ops@company.com (Ops Team)"
set replyto="support@company.com"
set smtp=smtp://smtp.company.com:587
set smtp-auth=login
set smtp-auth-user="ops@company.com"
set smtp-auth-password="your_password"
set ssl-verify=ignore
set charset=utf-8
set sendwait
配置後可簡化發送命令:
mail -s "Test" admin@example.com < /dev/null # 自動使用上述配置
| 問題 | 原因 | 解決 |
|---|---|---|
| 郵件發不出去 | MTA 未運行/配置錯、防火牆 25/587 端口、SPF/DKIM 缺失 | 檢查 mailq、postfix check、郵件伺服器日誌 |
| 進入垃圾箱 | 無 SPF/DKIM/DMARC、內容觸發規則 | 配置域名解析記錄、優化正文內容 |
| 中文亂碼 | 編碼未聲明 | set charset=utf-8,正文確為 UTF-8 |
| 附件無法打開 | 編碼/類型錯誤 | 用 uuencode 或 mutt 替代 |
| 發送緩慢 | DNS 解析慢、郵件伺服器灰名單 | 配置本地 DNS 緩存、申請白名單 |