Dynamic Django Mail Configuration

后端 未结 4 958
礼貌的吻别
礼貌的吻别 2020-12-17 21:20

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 = model         


        
4条回答
  •  醉梦人生
    2020-12-17 22:12

    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

提交回复
热议问题