Sendcorex
Bài thực hành

Gửi email bằng Python (Django) qua SMTP

smtplib cho script đơn giản, hoặc backend email của Django cho ứng dụng — cả hai qua cùng SMTP relay có xác thực.

Bởi đội ngũ Sendcorex·Cập nhật 21 thg 9, 2026·8 phút đọc

Cách 1: Python thuần với smtplib

import smtplib, os
from email.mime.text import MIMEText

api_key = os.environ["SENDCOREX_API_KEY"]

msg = MIMEText("You are in.", "html")
msg["Subject"] = "Welcome!"
msg["From"] = "Your App <hello@yourdomain.com>"
msg["To"] = "customer@example.com"

with smtplib.SMTP("smtp.sendcorex.com", 587) as server:
    server.starttls()
    server.login(api_key, api_key)
    server.send_message(msg)

Cách 2: backend email của Django

Trỏ backend có sẵn của Django tới relay trong settings.py:

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.sendcorex.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ["SENDCOREX_API_KEY"]
EMAIL_HOST_PASSWORD = os.environ["SENDCOREX_API_KEY"]
DEFAULT_FROM_EMAIL = "Your App <hello@yourdomain.com>"

Sau đó gửi từ bất kỳ đâu trong ứng dụng bằng send_mail() hoặc, với HTML, EmailMultiAlternatives:

from django.core.mail import EmailMultiAlternatives

email = EmailMultiAlternatives("Welcome!", "You are in.", to=["customer@example.com"])
email.attach_alternative("<h1>You are in.</h1>", "text/html")
email.send()

Lỗi thường gặp

Triệu chứngCách sửa
SMTPAuthenticationErrorXác nhận biến môi trường API key đã được đặt và dùng cho cả user lẫn password.
SMTPServerDisconnectedGọi starttls() trước login(), không phải sau.

Gửi email đầu tiên trong vài phút

Tạo tài khoản miễn phí, xác minh tên miền và dán code ở trên.

Không cần thẻ tín dụng