Milano
Milano

Reputation: 18745

How to use two different email addresses for emails sending?

I have a Django project which has two domains.

domain1.com
domain2.com

I use Sites application to differ between those two addresses like:

<h1>Welcome to {% if site.id==1 %}Domain1{% else %}Domain2</h1>

I want to be able to send messages from both emails:

    send_email(user, '[email protected]' if site.id==1 else '[email protected]', message...)

I tried add from_email to EmailMessage but it doesn't work. Sender is '[email protected]'.

mail = EmailMessage(subject, message, from_email='[email protected]', to=[user_email])
mail.send()

I have only one settings.py so I can set probably only one SMTP.

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'pswd'

Do you know how to make it work?

EDIT: So I tried this:

with get_connection(
        host=settings.EMAIL_HOST,
        port=settings.EMAIL_PORT,
        username='[email protected]',
        password='mypasswd',
        use_tls=settings.EMAIL_USE_TLS) as connection:
    EmailMessage(subject, message, [user.email],
                 connection=connection).send()

I've checked it - this code is being called. It doesn't return any Exception but it doesn't send email.

To be sure, I've tested this address and email inside settings.py as a global connection and it worked.

Upvotes: 1

Views: 1542

Answers (1)

Colwin
Colwin

Reputation: 2685

You can override the settings in your settings.py by using get_connection like this

from django.core.mail import get_connection, send_mail
from django.core.mail.message import EmailMessage

with get_connection(
    host=<host>, 
    port=<port>, 
    username=<username>, 
    password=<password>, 
    use_tls=<True/False>
) as connection:
    EmailMessage(subject, body, from, [to],
                 connection=connection).send()

Using with will close the connection automatically. If you don't use with you'll need to close the connection manually with connection.close()

Documentation is here -> https://docs.djangoproject.com/en/dev/topics/email/#email-backends

Upvotes: 2

Related Questions