Search code examples
djangodjango-email

How to set SMTP settings for each email on the fly?


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.


Solution

  • 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()