2017-08-01 149 views
1

我有一個Django項目,它有兩個域。如何使用兩個不同的電子郵件地址發送電子郵件?

domain1.com 
domain2.com 

我用Sites應用像這兩個地址之間的不同:

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

我希望能夠從兩個電子郵件發送消息:

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

我嘗試添加from_emailEmailMessage但它不起作用。發件人是'[email protected]'。

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

我只有一個settings.py,所以我可以設置大概只有一個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' 

你知道如何使它工作嗎?

編輯:所以,我想這一點:

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

我檢查了它 - 這個代碼將被調用。它不會返回任何異常,但不會發送電子郵件。

可以肯定,我已經在settings.py裏面測試過這個地址和電子郵件了,它是一個全局連接,它工作正常。

回答

2

您可以通過使用get_connection這樣

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

與使用將自動關閉連接覆蓋你的settings.py設置。如果不使用就需要使用connection.close()

文檔手動關閉連接就在這裏 - >https://docs.djangoproject.com/en/dev/topics/email/#email-backends

+0

感謝。不幸的是,這是行不通的。它不會返回任何異常,但不會發送任何電子郵件。我在問題的底部添加了我的代碼。我確定它被調用,並且我確信證書沒問題。 –

+0

奇怪的是,我在最近工作過的一個項目中使用過它,它在那裏工作。 – Colwin

+1

好的,現在它可以工作。我想我沒有改變任何東西......可能是gmail導致了這個問題。像往常一樣... –

相關問題