其實這個封禁配置是合理的

長期以來在各類雲端平台上都會有一個限制,不允許虛擬機向外部的Email 伺服器25 port 發送email。

我一直以為這個限制是針對整個Email 體系,包括smtps ,但,並不是,這個限制只針對於明文的25 port。

那麼這個限制就變得非常合理,因為當代Email 已經很少使用明文傳送,絕大部分是基於smtps,小部分明文要麼是因為Email server 陳舊,要麼是因為application 中的既有代碼無法修改,要麼就是垃圾郵件發送者。

之所以會提到這個問題,是因為我的server 上跑了很多crontab,有時候某一個crontab 失敗了但是卻無法知曉,在古早的年代,crontab 的email 可以隨意的發送到各大郵件服務提供商,現在當然是不行。

所以簡單的搜索了一下Internet,找到了一些解決方式,使用Amazon SES 是一種方式,反正你只是自己給自己的inbox 發嘛,但是,Email 再少,它也是要付錢的。

有沒有不要錢的呢?有。

可以使用Gmail 的app password 來配置使用Gmail 的smtps 發送email,由於它不是明文25 port 而是密文587 port,所以在各大雲端平台上並沒有什麼阻礙。

在Amazon Linux 2023 上使用Postfix 配置如下:

======Postfix@Amazon Linux 2023======
dnf install postfix -y
vi /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

cat > /etc/postfix/sasl_passwd <<'EOF'
[smtp.gmail.com]:587 yourname@gmail.com:yourapppassword
EOF

chmod 600 /etc/postfix/sasl_passwd

postmap /etc/postfix/sasl_passwd

systemctl enable postfix
service postfix restart

而在FreeBSD上,較新版本預置了一個 DMA(DragonFly Mail Agent) ,比古早的Sendmail 小很多,我一直不太明白為什麼Sendmail 那個龐然大物在FreeBSD 中生存了那麼多年,DMA 的配置比Postfix 更簡單一些。

=======FreeBSD======
vi /etc/dma/dma.conf

SMARTHOST smtp.gmail.com
PORT 587
AUTHPATH /etc/dma/auth.conf
SECURETRANSFER
STARTTLS

cat > /etc/dma/auth.conf <<'EOF'
yourname@gmail.com|smtp.gmail.com:yourapppassword
EOF

如果是在MacOS 上呢,也是可以配置的,這主要是因為我的Macbook 上也跑了一些crontab,而我需要知道他們執行是否成功或者失敗。

======MacOS======
brew install msmtp

vi ~/.msmtprc
defaults
auth on
tls on
tls_trust_file /etc/ssl/cert.pem

account gmail
host smtp.gmail.com
port 587
from yourname@gmail.com
user yourname@gmail.com
password yourapppassword

account default : gmail

chmod 600 ~/.msmtprc

echo 'set sendmail="/opt/homebrew/bin/msmtp"' | sudo tee -a /etc/mail.rc

sudo ln -sf /opt/homebrew/bin/msmtp /usr/local/bin/sendmail


最後一步是在 /etc/aliases 中添加目的地址,形如:
root: yourname@gmail.com

修改後,執行一下 /usr/bin/newaliases 讀取這個配置文件生成新的 /etc/aliases.db 。

特別說明:對於那些屏蔽了gmail 的國家而言,可以在互聯互通的服務器上使用socat 作為代理轉發。同理也可用於自己的客戶端收發gmail。

以FreeBSD為例:

sudo pkg install socat

sysrc socat_enable="YES"


vi /usr/local/etc/socat-instances.conf

add:

[gmailproxy]
daemonuser=root
flags="TCP-LISTEN:587,reuseaddr,fork TCP:smtp.gmail.com:587"

service socat start gmailproxy
service socat status gmailproxy

在需要收發gmail 的PC 上設置/etc/hosts ,將smtp.gmail.com 指向socat 所在的服務器IP地址,完成。