2012-01-19 48 views
1

背景: -如何自定義郵件後端的EmailMultiAlternatives在Django

我的郵箱後端是這樣的:

EMAIL_HOST ='smtp.gmail.com' 
EMAIL_PORT = 587 
EMAIL_HOST_USER = '[email protected]' 
EMAIL_HOST_PASSWORD = 'XXX' 
EMAIL_USE_TLS = True 

問題: -

我使用EmailMultiAlternatives發送HTML郵件。 現在我想定義auth_user和auth_password,以便我可以更改「from」。基本上我想要過度使用EMAIL_HOST_USER,但希望from_email是冗長的,即「支持團隊」。如何做呢?

subject, from_email, to = "hello", 'Support Team','[email protected]' 
text = "hello" 
html = "<strong>hello</strong>" 
msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) 
msg.attach_alternative(html_content, "text/html") 
msg.send(fail_silently=False,auth_user = '[email protected]',auth_password = 'XXX') 

回答

3

你可以做這樣的事情:

from django.core.mail import * 

#retrieve emailbackend from settings.py 
connection = get_connection(username, password) 
#change connection parameters 
connection.host='XXX' 
msg = EmailMultiAlternatives(subject, text_content, from_email, [to], connection) 
msg.attach_alternative(html_content, "text/html") 
+0

connection.close()時是不需要的。它會引發一個錯誤,因爲send_messages關閉了它打開的所有連接。 –

+0

當msg.send()拋出異常時,我能夠使用這個想法切換到備份SMTP服務器。很棒。 –

+0

您可以直接傳入連接。 –