|
15 | 15 | from pathlib import Path
|
16 | 16 |
|
17 | 17 | from plain.runtime import settings
|
| 18 | +from plain.templates import Template, TemplateFileMissing |
18 | 19 | from plain.utils.encoding import force_str, punycode
|
| 20 | +from plain.utils.html import strip_tags |
19 | 21 |
|
20 | 22 | from .utils import DNS_NAME
|
21 | 23 |
|
@@ -492,3 +494,68 @@ def _create_alternatives(self, msg):
|
492 | 494 | for alternative in self.alternatives:
|
493 | 495 | msg.attach(self._create_mime_attachment(*alternative))
|
494 | 496 | return msg
|
| 497 | + |
| 498 | + |
| 499 | +class TemplateEmail(EmailMultiAlternatives): |
| 500 | + def __init__( |
| 501 | + self, |
| 502 | + *, |
| 503 | + template, |
| 504 | + context=None, |
| 505 | + subject="", |
| 506 | + from_email=None, |
| 507 | + to=None, |
| 508 | + bcc=None, |
| 509 | + connection=None, |
| 510 | + attachments=None, |
| 511 | + headers=None, |
| 512 | + alternatives=None, |
| 513 | + cc=None, |
| 514 | + reply_to=None, |
| 515 | + ): |
| 516 | + self.template = template |
| 517 | + self.context = context or {} |
| 518 | + |
| 519 | + self.body_html, body = self.render_content() |
| 520 | + |
| 521 | + super().__init__( |
| 522 | + subject=subject, |
| 523 | + body=body, |
| 524 | + from_email=from_email, |
| 525 | + to=to, |
| 526 | + bcc=bcc, |
| 527 | + connection=connection, |
| 528 | + attachments=attachments, |
| 529 | + headers=headers, |
| 530 | + alternatives=alternatives, |
| 531 | + cc=cc, |
| 532 | + reply_to=reply_to, |
| 533 | + ) |
| 534 | + |
| 535 | + self.attach_alternative(self.body_html, "text/html") |
| 536 | + |
| 537 | + def get_template_context(self): |
| 538 | + return self.context |
| 539 | + |
| 540 | + def render_content(self): |
| 541 | + context = self.get_template_context() |
| 542 | + html_content = self.render_html(context) |
| 543 | + |
| 544 | + try: |
| 545 | + plain_content = self.render_plain(context) |
| 546 | + except TemplateFileMissing: |
| 547 | + plain_content = strip_tags(html_content) |
| 548 | + |
| 549 | + return html_content, plain_content |
| 550 | + |
| 551 | + def render_plain(self, context): |
| 552 | + return Template(self.get_plain_template_name()).render(context) |
| 553 | + |
| 554 | + def render_html(self, context): |
| 555 | + return Template(self.get_html_template_name()).render(context) |
| 556 | + |
| 557 | + def get_plain_template_name(self): |
| 558 | + return f"mail/{self.template}.txt" |
| 559 | + |
| 560 | + def get_html_template_name(self): |
| 561 | + return f"mail/{self.template}.html" |
0 commit comments