We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Subject with new line crashes email sending

Subject with new line crashes email sending


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `adhocracy4/emails/mixins.py`
Content:
```
1 from email.mime.image import MIMEImage
2 
3 from django.contrib.staticfiles import finders
4 from .base import EmailBase
5 
6 
7 class PlatformEmailMixin:
8     """
9     Attaches the static file images/logo.png so it can be used in an html
10     email.
11     """
12     def get_attachments(self):
13         attachments = super().get_attachments()
14         filename = (
15             finders.find('images/email_logo.png')
16             or finders.find('images/email_logo.svg')
17         )
18         if filename:
19             if filename.endswith('.png'):
20                 imagetype = 'png'
21             else:
22                 imagetype = 'svg+xml'
23 
24             with open(filename, 'rb') as f:
25                 logo = MIMEImage(f.read(), imagetype)
26 
27             logo.add_header('Content-ID', '<{}>'.format('logo'))
28             return attachments + [logo]
29         return attachments
30 
31 
32 class SyncEmailMixin(EmailBase):
33     """Send Emails synchronously."""
34 
35     @classmethod
36     def send(cls, object, *args, **kwargs):
37         """Call dispatch immediately"""
38         return cls().dispatch(object, *args, **kwargs)
39
```

Path: `adhocracy4/emails/base.py`
Content:
```
1 from django.conf import settings
2 from django.contrib.contenttypes.models import ContentType
3 from django.contrib.sites import models as site_models
4 from django.core.mail.message import EmailMultiAlternatives
5 from django.template.loader import select_template
6 from django.utils import translation
7 
8 from . import tasks
9 
10 
11 class EmailBase:
12     site_id = 1
13     object = None
14     template_name = None
15     fallback_language = 'en'
16     for_moderator = False
17 
18     def get_site(self):
19         return site_models.Site.objects.get(pk=self.site_id)
20 
21     def get_host(self):
22         site = self.get_site()
23         ssl_enabled = True
24         if site.domain.startswith('localhost:'):
25             ssl_enabled = False
26 
27         url = 'http{ssl_flag}://{domain}'.format(
28             ssl_flag='s' if ssl_enabled else '',
29             domain=site.domain,
30         )
31         return url
32 
33     def get_context(self):
34         object_context_key = self.object.__class__.__name__.lower()
35         return {
36             'email': self,
37             'site': self.get_site(),
38             object_context_key: self.object
39         }
40 
41     def get_receivers(self):
42         return []
43 
44     def get_attachments(self):
45         return []
46 
47     def get_languages(self, receiver):
48         return [translation.get_language(), self.fallback_language]
49 
50     def get_reply_to(self):
51         return None
52 
53     @classmethod
54     def send(cls, object, *args, **kwargs):
55         """Send email asynchronously.
56 
57         NOTE: args and kwargs must be JSON serializable.
58         """
59         ct = ContentType.objects.get_for_model(object)
60         tasks.send_async(
61             cls.__module__, cls.__name__,
62             ct.app_label, ct.model, object.pk,
63             args, kwargs)
64         return []
65 
66     def render(self, template_name, context):
67         languages = self.get_languages(context['receiver'])
68         template = select_template([
69             '{}.{}.email'.format(template_name, lang)
70             for lang in languages
71         ])
72 
73         # Get the actually chosen language from the template name
74         language = template.template.name.split('.', 2)[-2]
75 
76         with translation.override(language):
77             parts = []
78             for part_type in ('subject', 'txt', 'html'):
79                 context['part_type'] = part_type
80                 parts.append(template.render(context))
81                 context.pop('part_type')
82 
83         return tuple(parts)
84 
85     def dispatch(self, object, *args, **kwargs):
86         self.object = object
87         self.kwargs = kwargs
88         receivers = self.get_receivers()
89         context = self.get_context()
90         context.update(kwargs)
91         attachments = self.get_attachments()
92         template = self.template_name
93 
94         mails = []
95         for receiver in receivers:
96             context['receiver'] = receiver
97             (subject, text, html) = self.render(template, context)
98             context.pop('receiver')
99 
100             if hasattr(receiver, 'email'):
101                 to_address = receiver.email
102             else:
103                 to_address = receiver
104 
105             mail = EmailMultiAlternatives(
106                 subject=subject.strip(),
107                 body=text,
108                 from_email=settings.DEFAULT_FROM_EMAIL,
109                 to=[to_address],
110                 reply_to=self.get_reply_to(),
111             )
112 
113             if len(attachments) > 0:
114                 mail.mixed_subtype = 'related'
115 
116                 for attachment in attachments:
117                     mail.attach(attachment)
118 
119             mail.attach_alternative(html, 'text/html')
120             mail.send()
121             mails.append(mail)
122         return mails
123
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/adhocracy4/emails/base.py b/adhocracy4/emails/base.py
--- a/adhocracy4/emails/base.py
+++ b/adhocracy4/emails/base.py
@@ -1,3 +1,5 @@
+import re
+
 from django.conf import settings
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.sites import models as site_models
@@ -102,8 +104,10 @@
             else:
                 to_address = receiver
 
+            subject_clean = re.sub(r'[\r\n]', '', subject).strip()
+
             mail = EmailMultiAlternatives(
-                subject=subject.strip(),
+                subject=subject_clean,
                 body=text,
                 from_email=settings.DEFAULT_FROM_EMAIL,
                 to=[to_address],
diff --git a/adhocracy4/emails/mixins.py b/adhocracy4/emails/mixins.py
--- a/adhocracy4/emails/mixins.py
+++ b/adhocracy4/emails/mixins.py
@@ -1,7 +1,6 @@
 from email.mime.image import MIMEImage
 
 from django.contrib.staticfiles import finders
-from .base import EmailBase
 
 
 class PlatformEmailMixin:
@@ -29,7 +28,7 @@
         return attachments
 
 
-class SyncEmailMixin(EmailBase):
+class SyncEmailMixin:
     """Send Emails synchronously."""
 
     @classmethod

{"golden_diff": "diff --git a/adhocracy4/emails/base.py b/adhocracy4/emails/base.py\n--- a/adhocracy4/emails/base.py\n+++ b/adhocracy4/emails/base.py\n@@ -1,3 +1,5 @@\n+import re\n+\n from django.conf import settings\n from django.contrib.contenttypes.models import ContentType\n from django.contrib.sites import models as site_models\n@@ -102,8 +104,10 @@\n             else:\n                 to_address = receiver\n \n+            subject_clean = re.sub(r'[\\r\\n]', '', subject).strip()\n+\n             mail = EmailMultiAlternatives(\n-                subject=subject.strip(),\n+                subject=subject_clean,\n                 body=text,\n                 from_email=settings.DEFAULT_FROM_EMAIL,\n                 to=[to_address],\ndiff --git a/adhocracy4/emails/mixins.py b/adhocracy4/emails/mixins.py\n--- a/adhocracy4/emails/mixins.py\n+++ b/adhocracy4/emails/mixins.py\n@@ -1,7 +1,6 @@\n from email.mime.image import MIMEImage\n \n from django.contrib.staticfiles import finders\n-from .base import EmailBase\n \n \n class PlatformEmailMixin:\n@@ -29,7 +28,7 @@\n         return attachments\n \n \n-class SyncEmailMixin(EmailBase):\n+class SyncEmailMixin:\n     \"\"\"Send Emails synchronously.\"\"\"\n \n     @classmethod\n", "issue": "Subject with new line crashes email sending\n\nSubject with new line crashes email sending\n\n", "before_files": [{"content": "from email.mime.image import MIMEImage\n\nfrom django.contrib.staticfiles import finders\nfrom .base import EmailBase\n\n\nclass PlatformEmailMixin:\n    \"\"\"\n    Attaches the static file images/logo.png so it can be used in an html\n    email.\n    \"\"\"\n    def get_attachments(self):\n        attachments = super().get_attachments()\n        filename = (\n            finders.find('images/email_logo.png')\n            or finders.find('images/email_logo.svg')\n        )\n        if filename:\n            if filename.endswith('.png'):\n                imagetype = 'png'\n            else:\n                imagetype = 'svg+xml'\n\n            with open(filename, 'rb') as f:\n                logo = MIMEImage(f.read(), imagetype)\n\n            logo.add_header('Content-ID', '<{}>'.format('logo'))\n            return attachments + [logo]\n        return attachments\n\n\nclass SyncEmailMixin(EmailBase):\n    \"\"\"Send Emails synchronously.\"\"\"\n\n    @classmethod\n    def send(cls, object, *args, **kwargs):\n        \"\"\"Call dispatch immediately\"\"\"\n        return cls().dispatch(object, *args, **kwargs)\n", "path": "adhocracy4/emails/mixins.py"}, {"content": "from django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.sites import models as site_models\nfrom django.core.mail.message import EmailMultiAlternatives\nfrom django.template.loader import select_template\nfrom django.utils import translation\n\nfrom . import tasks\n\n\nclass EmailBase:\n    site_id = 1\n    object = None\n    template_name = None\n    fallback_language = 'en'\n    for_moderator = False\n\n    def get_site(self):\n        return site_models.Site.objects.get(pk=self.site_id)\n\n    def get_host(self):\n        site = self.get_site()\n        ssl_enabled = True\n        if site.domain.startswith('localhost:'):\n            ssl_enabled = False\n\n        url = 'http{ssl_flag}://{domain}'.format(\n            ssl_flag='s' if ssl_enabled else '',\n            domain=site.domain,\n        )\n        return url\n\n    def get_context(self):\n        object_context_key = self.object.__class__.__name__.lower()\n        return {\n            'email': self,\n            'site': self.get_site(),\n            object_context_key: self.object\n        }\n\n    def get_receivers(self):\n        return []\n\n    def get_attachments(self):\n        return []\n\n    def get_languages(self, receiver):\n        return [translation.get_language(), self.fallback_language]\n\n    def get_reply_to(self):\n        return None\n\n    @classmethod\n    def send(cls, object, *args, **kwargs):\n        \"\"\"Send email asynchronously.\n\n        NOTE: args and kwargs must be JSON serializable.\n        \"\"\"\n        ct = ContentType.objects.get_for_model(object)\n        tasks.send_async(\n            cls.__module__, cls.__name__,\n            ct.app_label, ct.model, object.pk,\n            args, kwargs)\n        return []\n\n    def render(self, template_name, context):\n        languages = self.get_languages(context['receiver'])\n        template = select_template([\n            '{}.{}.email'.format(template_name, lang)\n            for lang in languages\n        ])\n\n        # Get the actually chosen language from the template name\n        language = template.template.name.split('.', 2)[-2]\n\n        with translation.override(language):\n            parts = []\n            for part_type in ('subject', 'txt', 'html'):\n                context['part_type'] = part_type\n                parts.append(template.render(context))\n                context.pop('part_type')\n\n        return tuple(parts)\n\n    def dispatch(self, object, *args, **kwargs):\n        self.object = object\n        self.kwargs = kwargs\n        receivers = self.get_receivers()\n        context = self.get_context()\n        context.update(kwargs)\n        attachments = self.get_attachments()\n        template = self.template_name\n\n        mails = []\n        for receiver in receivers:\n            context['receiver'] = receiver\n            (subject, text, html) = self.render(template, context)\n            context.pop('receiver')\n\n            if hasattr(receiver, 'email'):\n                to_address = receiver.email\n            else:\n                to_address = receiver\n\n            mail = EmailMultiAlternatives(\n                subject=subject.strip(),\n                body=text,\n                from_email=settings.DEFAULT_FROM_EMAIL,\n                to=[to_address],\n                reply_to=self.get_reply_to(),\n            )\n\n            if len(attachments) > 0:\n                mail.mixed_subtype = 'related'\n\n                for attachment in attachments:\n                    mail.attach(attachment)\n\n            mail.attach_alternative(html, 'text/html')\n            mail.send()\n            mails.append(mail)\n        return mails\n", "path": "adhocracy4/emails/base.py"}], "after_files": [{"content": "from email.mime.image import MIMEImage\n\nfrom django.contrib.staticfiles import finders\n\n\nclass PlatformEmailMixin:\n    \"\"\"\n    Attaches the static file images/logo.png so it can be used in an html\n    email.\n    \"\"\"\n    def get_attachments(self):\n        attachments = super().get_attachments()\n        filename = (\n            finders.find('images/email_logo.png')\n            or finders.find('images/email_logo.svg')\n        )\n        if filename:\n            if filename.endswith('.png'):\n                imagetype = 'png'\n            else:\n                imagetype = 'svg+xml'\n\n            with open(filename, 'rb') as f:\n                logo = MIMEImage(f.read(), imagetype)\n\n            logo.add_header('Content-ID', '<{}>'.format('logo'))\n            return attachments + [logo]\n        return attachments\n\n\nclass SyncEmailMixin:\n    \"\"\"Send Emails synchronously.\"\"\"\n\n    @classmethod\n    def send(cls, object, *args, **kwargs):\n        \"\"\"Call dispatch immediately\"\"\"\n        return cls().dispatch(object, *args, **kwargs)\n", "path": "adhocracy4/emails/mixins.py"}, {"content": "import re\n\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.sites import models as site_models\nfrom django.core.mail.message import EmailMultiAlternatives\nfrom django.template.loader import select_template\nfrom django.utils import translation\n\nfrom . import tasks\n\n\nclass EmailBase:\n    site_id = 1\n    object = None\n    template_name = None\n    fallback_language = 'en'\n    for_moderator = False\n\n    def get_site(self):\n        return site_models.Site.objects.get(pk=self.site_id)\n\n    def get_host(self):\n        site = self.get_site()\n        ssl_enabled = True\n        if site.domain.startswith('localhost:'):\n            ssl_enabled = False\n\n        url = 'http{ssl_flag}://{domain}'.format(\n            ssl_flag='s' if ssl_enabled else '',\n            domain=site.domain,\n        )\n        return url\n\n    def get_context(self):\n        object_context_key = self.object.__class__.__name__.lower()\n        return {\n            'email': self,\n            'site': self.get_site(),\n            object_context_key: self.object\n        }\n\n    def get_receivers(self):\n        return []\n\n    def get_attachments(self):\n        return []\n\n    def get_languages(self, receiver):\n        return [translation.get_language(), self.fallback_language]\n\n    def get_reply_to(self):\n        return None\n\n    @classmethod\n    def send(cls, object, *args, **kwargs):\n        \"\"\"Send email asynchronously.\n\n        NOTE: args and kwargs must be JSON serializable.\n        \"\"\"\n        ct = ContentType.objects.get_for_model(object)\n        tasks.send_async(\n            cls.__module__, cls.__name__,\n            ct.app_label, ct.model, object.pk,\n            args, kwargs)\n        return []\n\n    def render(self, template_name, context):\n        languages = self.get_languages(context['receiver'])\n        template = select_template([\n            '{}.{}.email'.format(template_name, lang)\n            for lang in languages\n        ])\n\n        # Get the actually chosen language from the template name\n        language = template.template.name.split('.', 2)[-2]\n\n        with translation.override(language):\n            parts = []\n            for part_type in ('subject', 'txt', 'html'):\n                context['part_type'] = part_type\n                parts.append(template.render(context))\n                context.pop('part_type')\n\n        return tuple(parts)\n\n    def dispatch(self, object, *args, **kwargs):\n        self.object = object\n        self.kwargs = kwargs\n        receivers = self.get_receivers()\n        context = self.get_context()\n        context.update(kwargs)\n        attachments = self.get_attachments()\n        template = self.template_name\n\n        mails = []\n        for receiver in receivers:\n            context['receiver'] = receiver\n            (subject, text, html) = self.render(template, context)\n            context.pop('receiver')\n\n            if hasattr(receiver, 'email'):\n                to_address = receiver.email\n            else:\n                to_address = receiver\n\n            subject_clean = re.sub(r'[\\r\\n]', '', subject).strip()\n\n            mail = EmailMultiAlternatives(\n                subject=subject_clean,\n                body=text,\n                from_email=settings.DEFAULT_FROM_EMAIL,\n                to=[to_address],\n                reply_to=self.get_reply_to(),\n            )\n\n            if len(attachments) > 0:\n                mail.mixed_subtype = 'related'\n\n                for attachment in attachments:\n                    mail.attach(attachment)\n\n            mail.attach_alternative(html, 'text/html')\n            mail.send()\n            mails.append(mail)\n        return mails\n", "path": "adhocracy4/emails/base.py"}]}