我想实现django管理命令,该命令通过smtp发送电子邮件,而不是来自settings.py文件的默认设置,例如:
EMAIL_HOST
EMAIL_HOST_USER
EMAIL_HOST_PASSWORD
FROM_MAIL
EMAIL_USE_TLS
我希望使用与settings.py不同的替代设置发送,而不更改所有网站的电子邮件设置。
如何实现这个?
答案 0 :(得分:5)
定义备用电子邮件设置,然后使用这些设置创建新的邮件连接:
settings.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)