问题描述
很好地解释了让 Django 发送电子邮件这里 使用如下所示的标准设置.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'EMAIL_HOST = "mail.mysmtpserver.somewhere"#EMAIL_PORTEMAIL_HOST_USER = "我的@登录"EMAIL_HOST_PASSWORD = "我的密码"#EMAIL_USE_TLS = 真
然后使用django.core.mail.EmailMessage
来发送.
但是,如果您正在运行多个站点并且需要每个站点通过它们自己的 SMTP 服务器发送电子邮件(或者只是在同一个 SMTP 服务器中进行不同的登录),该怎么办?
搜索这样的 EmailBackend 或使用当前后端执行此操作的方法没有产生任何令人满意的结果.
如果您想覆盖提供的设置,您可以创建自己的连接并将其提供给 send_email
或 EmailMessage代码>
from django.core.mail import get_connection, send_mail从 django.core.mail.message 导入 EmailMessage# TODO: 插入巧妙的设置机制我的主机=''我的端口 = 587我的用户名 = ''我的密码=''my_use_tls = 真连接 = 获取连接(主机 = 我的主机,端口=我的端口,用户名=我的用户名,密码=我的密码,use_tls=my_use_tls)send_mail('dieditwork?', '测试邮件', 'from_email', ['to'], connection=connection)# 或者EmailMessage('diditwork?', 'test message', 'from_email', ['to'], connection=connection).send(fail_silently=False)
更新:确保在使用后关闭连接,@michel.iamit 答案指向显示连接已缓存以供 smpt 的代码.@dhackner 回答展示了如何使用 with 语句自动关闭连接.
Getting Django to send an email is nicely explained here using standard settings as shown below.
Then using django.core.mail.EmailMessage
to send it of.
How ever, what if you are running multiple sites and need each of these to send email through their own SMTP server (or just different login in the same SMTP server)?
Searching for a EmailBackend like this or a way to do it with the current backend did not produce any satisfactory results.
If you want to override the provided settings you can just create your own connection and provide it to send_email
or EmailMessage
from django.core.mail import get_connection, send_mail
from django.core.mail.message import EmailMessage
# TODO: Insert clever settings mechanism
my_host = ''
my_port = 587
my_username = ''
my_password = ''
my_use_tls = True
connection = get_connection(host=my_host,
port=my_port,
username=my_username,
password=my_password,
use_tls=my_use_tls)
send_mail('diditwork?', 'test message', 'from_email', ['to'], connection=connection)
# or
EmailMessage('diditwork?', 'test message', 'from_email', ['to'], connection=connection).send(fail_silently=False)
Update: Make sure to close the connection after use, @michel.iamit answer points to code showing the connection is cached for smpt. @dhackner answer shows how to automatically close a connection using with statement.
这篇关于EmailBackend 用于在 Django 中通过多个 SMTP 发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!