0

We can configure SMTP settings globally by defining these variables in the settings.py:

EMAIL_HOST = 'SMTP_HOST'
EMAIL_PORT = 'SMTP_PORT'
EMAIL_HOST_USER = 'SMTP_USER'
EMAIL_HOST_PASSWORD = 'SMTP_PASSWORD'

I want to set these parameters different for each email. How can I define the SMTP settings on the fly? I mean just before the sending.

Umut Çağdaş Coşkun
  • 1,197
  • 2
  • 15
  • 33

1 Answers1

4

EmailMessage class provides you with this option

First step is to configure your email backend

from django.core.mail import EmailMessage
from django.core.mail.backends.smtp import EmailBackend
connection = EmailBackend(
    host=your_host, port=your_port, username=your_username, 
    password=your_password, use_tls=True, fail_silently=fail_silently
)

Then all you have to do is use your connection settings

email = EmailMessage(
    subject=subject,
    body=body, 
    from_email=from_email, 
    to=[list_of_recipents, ], 
    connection=connection
)

email.send()
sebb
  • 1,956
  • 1
  • 16
  • 28