Hướng dẫn cấu hình gửi email từ VPS Google bằng SendGrid miễn phí

Hướng dẫn cấu hình gửi email từ VPS Google bằng SendGrid miễn phí

Trong bài này mình sẽ hướng dẫn các bạn cấu hình gửi email cho VPS của Google bằng SendGrid miễn phí (15.000 mail/tháng – một số không nhỏ cho nhu cầu cá nhân).

Mục lục

Đăng ký API SendGrid

  1. Đầu tiên bạn cần có VPS Google, xem hướng dẫn đăng ký https://quannguyenphat.com/huong-dan-dang-ky-vps-google-free-300-va-cai-dat-hocvps-tren-vps-google/

2. Vào Google Cloud Marketplace đăng ký dịch vụ gửi mail của SendGrid. Các bạn nhớ lưu lại thông tin SendGrid SMTP account: username, password và hostname. Hostname của SendGrid là smtp.sendgrid.net

3. Tạo API key:

a. Đăng nhập SendGrid với tài khoản bạn lưu ở trên rồi vào Settings > API Keys

b. Create an API key

c. Chọn quyền cho key. Ít nhất cần có quyền Mail send để gửi mail. Bạn chọn như mặc định là được. (Dòng trên cùng)

d. Click Save để tạo key.

e. Lưu lại key ở 1 nơi khác, vì SendGrid sẽ không hiện key nữa.

Cấu hình gửi mail với Postfix

  1. Đăng  nhập VPS bằng SSH

2. Lấy quyền root

sudo su -

3. Cài lớp an toàn

umask 077

4. Cài Postfix Mail Transport Agent:

yum install postfix cyrus-sasl-plain cyrus-sasl-md5 -y

5. Thay đổi cấu hình Postfix

nano /etc/postfix/main.cf

6. Cập nhật file

Thêm vào cuối file

# default_transport = error
# relay_transport = error
relayhost = [smtp.sendgrid.net]:2525
smtp_tls_security_level = encrypt
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
header_size_limit = 4096000
smtp_sasl_security_options = noanonymous

7. Save và đóng file

8. Thêm API key

echo [smtp.sendgrid.net]:2525 apikey:your-api-key >> /etc/postfix/sasl_passwd

Thay your-api-key bằng Key bạn lưu ở bước đầu.

9. Chạy tiếp lệnh để tạo file .db

postmap /etc/postfix/sasl_passwd

10. Xác thực file

ls -l /etc/postfix/sasl_passwd*

Hiện như sau là đúng

-rw------- 1 root root    ...  /etc/postfix/sasl_passwd
-rw------- 1 root root    ...  /etc/postfix/sasl_passwd.db

11. Xóa file lưu password

rm /etc/postfix/sasl_passwd

12. Thay đổi quyền của file .db và kiểm tra file đã xóa chưa

chmod 600 /etc/postfix/sasl_passwd.db
ls -la /etc/postfix/sasl_passwd.db

Hiện như sau là đúng

-rw------- 1 root root    ...  /etc/postfix/sasl_passwd.db

13. Tải lại cấu hình

postfix reload

Nếu chạy lênh này mà bị báo postfix/postfix-script: fatal: the Postfix mail system is not running thì bạn chạy lệnh

service postfix start

rồi chạy lệnh

service postfix reload

14. Cài đặt gói mailutils hoặc mailx

yum install mailx -y

15. Gửi mail kiểm tra

echo 'message' | mail -s subject [email protected]

Thay các thông số

  • message: Nội dung email
  • subject: tiêu đề email
  • [email protected]: địa chỉ nhận email

Kiểm tra bạn đã nhân được email chưa.

Có thể test bằng lệnh sau, nếu status phản hồi code 250 là thành công

tail -n 5 /var/log/maillog

Chúc các bạn thành công, nếu có thắc mắc hãy để lại bình luận.