我想实现 django 管理命令,该命令通过 smtp 发送电子邮件,而不是 settings.py 文件中的默认设置,例如:
EMAIL_HOST
EMAIL_HOST_USER
EMAIL_HOST_PASSWORD
FROM_MAIL
EMAIL_USE_TLS
我想使用不同于 settings.py 的替代设置发送而不更改所有站点的电子邮件设置。
如何实施?
定义您的备用电子邮件设置,然后使用这些设置创建新的邮件连接:
设置.py
ALTERNATE_EMAIL_HOST_PASSWORD = 'your password'
ALTERNATE_EMAIL_HOST_USER = 'your user'
ALTERNATE_EMAIL_HOST = ''
ALTERNATE_EMAIL_PORT = 123
ALTERNATE_EMAIL_USE_TLS = True
然后使用这些设置创建新连接:
from django.core import mail
from django.core.mail import send_mail
from django.conf import settings
# create new connection
connection = mail.get_connection()
connection.password = settings.ALTERNATE_EMAIL_HOST_PASSWORD
connection.username = settings.ALTERNATE_EMAIL_HOST_USER
connection.host = settings.ALTERNATE_EMAIL_HOST
connection.port = settings.ALTERNATE_EMAIL_PORT
connection.use_tls = settings.ALTERNATE_EMAIL_USE_TLS
# send email using new connection you just created
send_mail('my subject', 'my message', settings.DEFAULT_FROM_EMAIL,
['abc@gmail.com'], connection=connection)