Django易于使用的基于类的电子邮件
django-generic-mail的Python项目详细描述
易于使用,django基于类的电子邮件。
问题
我们的django项目没有统一的方式发送电子邮件。Django自己的电子邮件功能需要太多样板文件 代码和不够智能。它们也不是基于阶级的。
发送电子邮件应该与创建电子邮件类的实例、提供一段文本和调用 send()方法。这是最简单,最常见的情况。也可以覆盖基本模板, 提供单独的文本和HTML版本,将邮件发送到队列等。
这门课对你有什么帮助
- 如果:
- 有一个自定义文本模板,或
- 使用默认模板时,如果设置了文本体
- 如果:
- 有一个自定义HTML模板,或
- 当使用默认模板时,如果设置了html_body
- 当只有HTML实体时,也可以强制发送文本电子邮件。然后它将为您将HTML转换为文本。
- 当只有文本体时,也可以强制发送HTML电子邮件。然后它会为您将文本转换为html。
它不会做什么
这个电子邮件类不知道邮件队列。您可以使用自定义电子邮件后端或类似的项目 https://github.com/jtauber/django-mailer为了这个。
安装
$ pip install django-generic-mail
用法
from generic_mail import Email # This will send text email only, uses the email/base_text_email.html template with the "body" template variable email = Email('to@example.com', 'Subject', 'Line one\n\nLine two') email.send() # This will send text- and html email, also with default template email = Email('to@example.com', 'Subject', 'Line one\n\nLine two', '<p>Line one</p><p>Line two</p>') email.send() # This will send text- and html email, will convert text to html using Markdown email = Email('to@example.com', 'Subject', 'Line one\n\nLine two') email.send(text=True, html=True) # This will send html email only email = Email('to@example.com', 'Subject', html_body='<p>Line one</p><p>Line two</p>') email.send() # This will send text- and html email, will convert html to text by removing html tags, converting paragraphs and breaks email = Email('to@example.com', 'Subject', html_body='<p>Line one</p><p>Line two</p>') email.send(text=True, html=True) # This will send text email only, since there is no body given, the text must be in the templates email = Email('to@example.com', 'Subject', text_template='email/my_text_email.html') email.send() # This will send html email only, since there is no body given, the text must be in the templates email = Email('to@example.com', 'Subject', html_template='email/my_html_email.html') email.send() # This will send text- and html email, since there is no body given, the text must be in the templates email = Email('to@example.com', 'Subject', text_template='email/my_text_email.html', html_template='email/my_html_email.html') email.send() # This will generate an error: when proving only one custom template, you can't send both email versions email = Email('to@example.com', 'Subject', html_template='email/my_html_email.html') email.send(text=True, html=True) # This will generate an error: when using default templates, you need to give at least one body (text or html) email = Email('to@example.com', 'Subject') email.send()
子类化
如果您想创建自己的子类,它具有不同的默认值(其他模板、主题等),最好的方法是 这是通过更改类属性而不是重写__init__方法实现的。