Skip to content

Commit

Permalink
Fix saving html emails that have quoted_printable transfer (#420)
Browse files Browse the repository at this point in the history
* Fix saving html emails that have quoted_printable transfer

See #419

* Quopri returns bytestring, convert to utf-8

* Update backends.py

* Update backends.py

I've been thinking about this. I don't like to step into a decoding loophole. 

Because according to the Django docs always an EmailMessage class gets to the backend (https://docs.djangoproject.com/en/4.1/topics/email/#email-backends), we could simplify the way we get the body and html_body without doing any decoding.

* Update backends.py

minor fix

* Update backends.py

Minor fix for no html_body
  • Loading branch information
gabn88 authored Dec 5, 2022
1 parent 6a28859 commit 1d833db
Showing 1 changed file with 8 additions and 16 deletions.
24 changes: 8 additions & 16 deletions post_office/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@
from email.mime.base import MIMEBase
from django.core.files.base import ContentFile
from django.core.mail.backends.base import BaseEmailBackend

import quopri
from .settings import get_default_priority


class EmailBackend(BaseEmailBackend):

def open(self):
Expand Down Expand Up @@ -34,19 +33,12 @@ def send_messages(self, email_messages):
if email_message.reply_to:
reply_to_header = ", ".join(str(v) for v in email_message.reply_to)
headers.setdefault("Reply-To", reply_to_header)
message = email_message.message()

# Look for first 'text/plain' and 'text/html' alternative in email
plaintext_body = html_body = ''
for part in message.walk():
if part.get_content_type() == 'text/plain':
plaintext_body = part.get_payload()
if html_body:
break
if part.get_content_type() == 'text/html':
html_body = part.get_payload()
if plaintext_body:
break
message = email_message.body # The plaintext message is called body
html_body = '' # The default if no html body can be found
if hasattr(email_message, 'alternatives') and len(email_message.alternatives) > 0:
for alternative in email_message.alternatives:
if alternative[1] == 'text/html':
html_body = alternative[0]

attachment_files = {}
for attachment in email_message.attachments:
Expand All @@ -62,7 +54,7 @@ def send_messages(self, email_messages):
email = create(sender=from_email,
recipients=email_message.to, cc=email_message.cc,
bcc=email_message.bcc, subject=subject,
message=plaintext_body, html_message=html_body,
message=message, html_message=html_body,
headers=headers)

if attachment_files:
Expand Down

0 comments on commit 1d833db

Please sign in to comment.