Skip to content

Commit 27a5ae8

Browse files
authored
Perform unfolding of headers when parsing message (#71)
* ✅ [#70] Test newlines not being added to subject * ✨ [#70] Add the email.policy.EmailPolicy https://docs.python.org/3/library/email.policy.html#email.policy.EmailPolicy This results in the unfolding of headers that have previously been folded, so that new lines don't cause errors.
1 parent b9523a8 commit 27a5ae8

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

django_yubin/models.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import datetime
22
import logging
3+
import email
4+
from email import policy
35
from email import encoders as Encoders
46
from email.mime.base import MIMEBase
57

@@ -15,7 +17,7 @@
1517
from django.utils.text import Truncator
1618
from django.utils.timezone import now
1719
from django.utils.translation import gettext_lazy as _
18-
import mailparser
20+
from mailparser import MailParser
1921

2022
from . import mailparser_utils, tasks
2123

@@ -131,7 +133,8 @@ def recipients(self):
131133
return self.to() + self.cc() + self.bcc()
132134

133135
def get_message_parser(self):
134-
return mailparser.parse_from_string(self.message_data)
136+
message = email.message_from_string(self.message_data, policy=policy.default)
137+
return MailParser(message)
135138

136139
def get_email_message(self):
137140
"""

tests/tests/test_models.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from email.generator import _fmt
44
from unittest.mock import patch
55

6-
from django.core.mail import EmailMultiAlternatives
6+
from django.core.mail import EmailMessage, EmailMultiAlternatives
77
from django.test import TestCase
88
from django.utils import timezone
99

@@ -200,3 +200,26 @@ def reset_mock():
200200
with self.subTest("compare message as_string"):
201201
self.assertEqual(reconstructed_msg.as_string(), ref_as_string)
202202
reset_mock()
203+
204+
def test_email_with_long_subject(self):
205+
email_message = EmailMessage(
206+
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor "
207+
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
208+
"laboris nisi ut aliquip ex ea commodo consequat.",
209+
"Message body",
210+
211+
212+
)
213+
214+
message = Message.objects.create(
215+
to_address=','.join(email_message.to),
216+
cc_address=','.join(email_message.cc),
217+
bcc_address=','.join(email_message.bcc),
218+
from_address=email_message.from_email,
219+
subject=email_message.subject,
220+
message_data=email_message.message().as_string(),
221+
)
222+
223+
parsed_message = message.get_email_message()
224+
225+
self.assertNotIn("\n", parsed_message.subject)

0 commit comments

Comments
 (0)