方法1:smtplibでシンプルなPython
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)
方法2:Djangoのメールバックエンド
settings.pyで、Django標準のバックエンドをリレーに向けます:
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>"
あとはアプリのどこからでもsend_mail()で、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()
よくあるエラー
| 症状 | 対処 |
|---|---|
SMTPAuthenticationError | APIキーの環境変数が設定され、userとpasswordの両方に使われているか確認してください。 |
SMTPServerDisconnected | starttls()はlogin()の後ではなく、前に呼び出してください。 |