Make Django build-in send_mail function working with html by default

做~自己de王妃 提交于 2019-12-04 11:38:14

From Django docs: http://docs.djangoproject.com/en/dev/topics/email/#sending-alternative-content-types

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

No send_mail() required.

Sounds like a lot of people are misreading your question.

To override the import from third party modules, overwriting sys.modules['django.core.mail'] might work.

It works in simple tests, but it's not thoroughly tested.

import sys
from django.core import mail 

def my_send_mail(*args, **kwargs):
    print "Sent!11"

mail.send_mail = my_send_mail
sys.modules['django.core.mail'] = mail


from django.core.mail import send_mail
send_mail('blah')
# output: Sent!11

For example, if I put that code in my settings.py and launch the manage.py shell and import send_mail, I get my version.

My shell session

In [1]: from django.core.mail import send_mail
In [2]: send_mail()
Sent!11

Disclaimer
I've never done anything like this and don't know if there are any funky ramifications.

I wrote application for quickly switching from plain-text emails to html based emails for all project's applications. It will work without modifying any Django code or code of other third-part applications.

Check it out here: https://github.com/ramusus/django-email-html

How about changing django a little and substituting original code with your own function? You can actually just add your own function and don't remove the old, as the last definition will be imported. I don't like such solutions, because I don't like patching external libraries (you need to remember about patching them again when you upgrade), but this would solve your problem quickly.

In Django 1.7 added extra attribute html_message to send_mail() function to send html message.

https://docs.djangoproject.com/en/1.8/topics/email/#send-mail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!