动态Django邮件配置

yet*_*yet 8 python email django

我不想在setting.py中使用电子邮件配置字段,我想将它们放入模型中.

class Configuration(models.Model):
    email_use_tls = models.BooleanField(_(u'EMAIL_USE_TLS'),default=True)
    email_host = models.CharField(_(u'EMAIL_HOST'),max_length=1024)
    email_host_user = models.CharField(_(u'EMAIL_HOST_USER'),max_length=255)
    email_host_password = models.CharField(_(u'EMAIL_HOST_PASSWORD'),max_length=255)
    email_port = models.PositiveSmallIntegerField(_(u'EMAIL_PORT'),default=587)
    ....
Run Code Online (Sandbox Code Playgroud)

配置django.core.mail.send_mail行为的最佳做法是什么?我应该将send_mail代码复制到我的项目中吗?那不是我想要的.

And*_*bin 13

非常有趣的问题.看起来这已经在EmailMessage类中实现了.

首先,您需要配置电子邮件后端

from django.core.mail import EmailMessage
from django.core.mail.backends.smtp import EmailBackend


config = Configuration.objects.get(**lookup_kwargs)

backend = EmailBackend(host=config.host, port=congig.port, username=config.username, 
                       password=config.password, use_tls=config.use_tls, fail_silently=config.fail_silently)
Run Code Online (Sandbox Code Playgroud)

然后只需将连接传递给EmailMessage

email = EmailMessage(subject='subj', body='body', from_email=from_email, to=to, 
             connection=backend)
Run Code Online (Sandbox Code Playgroud)

然后发送邮件:)

email.send()
Run Code Online (Sandbox Code Playgroud)

如果您想要html或文件附件,请使用EmailMultiAlternatives代替