คู่มือนี้สอนส่งอีเมลจาก Linux Command Line และ Shell Script ด้วย mail (Simple) และ mutt (รองรับ Attachment)
ข้อกำหนดเบื้องต้น
- MTA (Mail Transfer Agent) ติดตั้งและทำงาน: Postfix, Exim, Sendmail, msmtp
- ตั้งค่า Relay/Smarthost (Gmail, SendGrid, AWS SES) สำหรับส่งออกรับนอก
- ทดสอบ:
echo test | mail -s test user@example.com
1. คำสั่ง mail (mailx / bsd-mailx)
ส่งอีเมลพื้นฐาน
# Interactive (พิมพ์ Body แล้ว Ctrl+D)
mail -s "Subject" user@example.com
# Pipe จาก Echo
echo "Body text" | mail -s "Subject" user@example.com
# อ่าน Body จากไฟล์
mail -s "Subject" user@example.com < /path/to/file.log
Options
| Option | คำอธิบาย |
-s | Subject |
-c | CC (Carbon Copy) |
-b | BCC (Blind Carbon Copy) |
-a | Attachment (บาง Version ไม่รองรับ) |
-r | From Address |
ตัวอย่างครบ
echo "Welcome" | mail -s "Hello" user@example.com -c cc@example.com -b bcc@example.com
2. Mutt (รองรับ Attachment จริง)
# ติดตั้ง
sudo apt install mutt
# หรือ
sudo dnf install mutt
ส่งอีเมลพร้อม Attachment
echo "Body text" | mutt -a /path/file.zip -s "Subject" user@example.com
# หลาย Attachment
echo "Body" | mutt -a file1.zip -a file2.pdf -s "Subject" user@example.com
# ไม่มี Body (Empty)
echo "" | mutt -a backup.tar.gz -s "Backup" user@example.com
3. ส่งอีเมลจาก Shell Script
Script 1: Disk Usage Report
#!/bin/bash
df -h | mail -s "Disk Space Report - $(hostname)" admin@example.com
Script 2: Disk + Memory Report (Multi-line)
#!/bin/bash
df -h > /tmp/report.log
free -h >> /tmp/report.log
mail -s "System Report - $(date +%F)" admin@example.com < /tmp/report.log
Script 3: Backup + Email Attachment
#!/bin/bash
tar -czf /tmp/backup.tar.gz /home/user/data
echo "Daily backup attached" | mutt -a /tmp/backup.tar.gz -s "Daily Backup $(date +%F)" admin@example.com
rm /tmp/backup.tar.gz
การตั้งค่า Postfix สำหรับ Gmail Relay (Ubuntu)
# 1. ติดตั้ง
sudo apt install postfix mailutils libsasl2-modules
# 2. แก้ไข /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_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_use_tls = yes
# 3. สร้าง /etc/postfix/sasl_passwd
[smtp.gmail.com]:587 your_email@gmail.com:your_app_password
# 4. Hash และ Secure
postmap /etc/postfix/sasl_passwd
chmod 600 /etc/postfix/sasl_passwd*
# 5. Restart
systemctl restart postfix
Best Practices
- ใช้ App Password ไม่ใช่รหัสผ่านจริง (Gmail, Outlook)
- จำกัดขนาด Attachment (Email Server มักจำกัด 25MB)
- ใช้ MIME/Encoding ถูกต้องสำหรับภาษาไทย
- Monitor Mail Queue:
mailq, postqueue -p
- Log:
/var/log/mail.log หรือ journalctl -u postfix
การส่งอีเมลจาก Command Line/Script เป็นพื้นฐานของ System Monitoring และ Automation