Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django sending email with dynamic SMTP settings

I am trying to make EMAIL_HOST settings configurable within admin and I will create a model with required fields like:

  • EMAIL_HOST
  • EMAIL_HOST_USER
  • EMAIL_HOST_PASSWORD
  • EMAIL_PORT

But how can I use those fields in views using send_mail?

like image 895
ratata Avatar asked Oct 12 '25 15:10

ratata


2 Answers

If you want to use send_mail, you'll have to create your own email backend which uses your custom settings and then pass it to send_mail in the connection attribute.

like image 50
Burhan Khalid Avatar answered Oct 14 '25 03:10

Burhan Khalid


This works for me

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

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

try:

    backend = EmailBackend(
        host=config.host,
        port=config.port,
        password=config.password,
        username=config.username,
        use_tls=config.use_tls,
        fail_silently=config.fail_silently
    )

    mail = EmailMessage(
        subject="subject",
        body="body",
        from_email=config.username,
        to=["[email protected]"],
        connection=backend,
    )
    mail.send()

except Exception as err:
    print(err)
like image 28
Masoud Aghaei Avatar answered Oct 14 '25 05:10

Masoud Aghaei