萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 終端機寄送郵件完全指南:mail/mailx、附件、SMTP 設定與自動化腳本

Linux 系統內建 mail (或 mailx, mutt, sendmail) 等郵件用戶代理程式 (MUA),配合本地 MTA (Postfix/Exim/Sendmail) 或外部 SMTP Relay,即可在終端機、Shell 腳本、Cron 任務中發送郵件。本文涵蓋基本指令、附件寄送、HTML 郵件、外部 SMTP 認證設定、自動化腳本範例。

Linux 郵件指令示意圖

一、基礎指令:mail / mailx

常見套件:mailutils (Debian/Ubuntu, 含 mail)、mailx (RHEL/CentOS, 連結至 mail)、bsd-mailx。

互動模式寄送

mail -s "Report Subject" recipient@example.com
# 輸入郵件正文 (多行)
# 結束輸入:Ctrl+D (EOF)
# 提示 Cc: 可輸入副本地址或直接 Enter

管道/重導向非互動寄送 (腳本適用)

# 從標準輸入讀取正文
echo "Body text" | mail -s "Subject" user@example.com

# 從檔案讀取正文
mail -s "Log Report" admin@example.com < /var/log/syslog

# 指定副本 (Cc) 與密件副本 (Bcc)
mail -s "Subject" -c "cc1@example.com,cc2@example.com" -b "bcc@example.com" to@example.com < body.txt

二、寄送附件 (需 mailx 支援 -a 選項或使用 mutt)

mailx (Heirloom mailx / s-nail) 支援 -a 附件:

mailx -s "Backup Report" -a /backup/db.sql.gz admin@example.com < /dev/null
# 或
echo "See attachment" | mailx -s "Subject" -a file.pdf -a image.png recipient@example.com

通用方案:使用 mutt (功能最強、支援 MIME/HTML/附件/多收件人)

sudo apt install mutt   # 或 yum install mutt

# 寄送附件
echo "Body" | mutt -s "Subject" -a /path/file.pdf -- recipient@example.com

# 寄送 HTML 郵件
mutt -e "set content_type=text/html" -s "HTML Report" -- recipient@example.com < report.html

# 多附件、多收件人
mutt -s "Subject" -a file1.pdf -a file2.png -c cc@example.com -b bcc@example.com -- to1@example.com to2@example.com < body.txt

三、配置外部 SMTP Relay (Gmail、Outlook、企業郵箱)

本地 MTA (Postfix) 直發常被視為垃圾郵件。推薦配置 **SMTP Relay (Smart Host)** 透過可信郵件伺服器轉發。

方案 A:Postfix 配置 Relay (系統級,所有 mail/mutt 共用)

# /etc/postfix/main.cf
relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

# /etc/postfix/sasl_passwd
[smtp.gmail.com]:587    your_email@gmail.com:your_app_password

# 建立 hash 資料庫並重啟
sudo postmap /etc/postfix/sasl_passwd
sudo systemctl restart postfix

Gmail 需開啟「兩步驟驗證」並產生「應用程式密碼」。

方案 B:msmtp (輕量級 SMTP 客戶端,指定給特定用戶/腳本)

# 安裝
sudo apt install msmtp msmtp-mta

# 配置 ~/.msmtprc (權限 600)
account default
host smtp.gmail.com
port 587
auth on
tls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
user your_email@gmail.com
password your_app_password
from your_email@gmail.com
logfile ~/.msmtp.log

# 設定為系統預設 sendmail (可選)
# ln -sf /usr/bin/msmtp /usr/sbin/sendmail

之後直接用 mail、mutt、sendmail 即可透過 msmtp 發信。

四、進階:HTML 郵件、內嵌圖片、優先級、編碼

# 使用 mutt 發送 HTML + 內嵌圖片 (CID)
mutt -e "set content_type=text/html" \
     -s "HTML Report" \
     -a report.html \
     -- recipient@example.com < /dev/null
# 內嵌圖片需在 HTML 用  並用 mutt 多重附件 (較複雜),建議改用 Python smtplib 郵件庫

Python smtplib 完整範例 (支援 HTML、附件、內嵌圖片、SSL/TLS)


import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
from email.header import Header

def send_mail(smtp_host, port, user, pwd, to_list, subject, html_body, attachments=[], inline_images={}):
    msg = MIMEMultipart('related')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = user
    msg['To'] = ', '.join(to_list)

    msg_alternative = MIMEMultipart('alternative')
    msg.attach(msg_alternative)
    msg_alternative.attach(MIMEText(html_body, 'html', 'utf-8'))

    # 內嵌圖片
    for cid, img_path in inline_images.items():
        with open(img_path, 'rb') as f:
            img = MIMEImage(f.read())
            img.add_header('Content-ID', f'<{cid}>')
            msg.attach(img)

    # 附件
    for att_path in attachments:
        with open(att_path, 'rb') as f:
            part = MIMEApplication(f.read(), Name=att_path.split('/')[-1])
        part['Content-Disposition'] = f'attachment; filename="{att_path.split("/")[-1]}"'
        msg.attach(part)

    with smtplib.SMTP(smtp_host, port) as server:
        server.starttls()
        server.login(user, pwd)
        server.send_message(msg)

# 使用
send_mail('smtp.gmail.com', 587, 'you@gmail.com', 'app_pwd',
          ['target@example.com'],
          'Test', '

Hello

', attachments=['/tmp/report.pdf'], inline_images={'chart': '/tmp/chart.png'})

五、自動化場景最佳實踐

  • Cron 任務發送報表: 腳本中捕獲命令輸出,失敗時寄送錯誤通知。
    0 6 * * * /backup.sh 2>&1 | mailx -s "Backup $(date +\%F) Status: $?" admin@example.com
        
  • 日誌監控告警: grep -q "ERROR" /var/log/app.log && mail -s "App ERROR Alert" ops@example.com < /var/log/app.log。
  • 編碼統一 UTF-8: 環境變數 LANG=zh_TW.UTF-8,郵件主體/主旨指定 charset。
  • 速率限制: 避免大量郵件觸發 SMTP 限流,佇列機制 (Postfix) 自動處理重試。

六、收信 (簡略)

mail                 # 進入互動式收信介面
# 指令: 數字=閱讀, d=刪除, r=回覆, q=退出存檔, x=退出不存

# 非互動列出
mail -H
# 或用 mutt -f /var/mail/user

總結

Linux 終端機寄信三層次選擇:mail/mailx (簡單純文字/附件)、mutt (功能豐富、支援 HTML/MIME)、Python smtplib (程式化完全控制、企業級應用整合)。**核心關鍵在於配置可靠的 SMTP Relay (Postfix/msmtp)**,解決送達率與認證問題。自動化腳本務必處理編碼、錯誤捕獲與速率控制。

copyright © 萬盛學電腦網 all rights reserved