Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

python - Dynamic Django Mail Configuration

I don't want to use email configuration fields in setting.py, i want to put them in to a model.

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)
    ....

What is the best practice to configure django.core.mail.send_mail behaviour? Should i copy send_mail code to my project? Thats not what i want.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Very interesting question. It seems like this is already implemented in EmailMessage class.

First you need to configure email backend

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)

Then just pass connection to EmailMessage

email = EmailMessage(subject='subj', body='body', from_email=from_email, to=to, 
             connection=backend)

Then send email :)

email.send()

Ofc if you want html or file attachments use EmailMultiAlternatives instead


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...