prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  email sender address fallback is incorrect
  ## Current Behavior
  
  ![image](https://user-images.githubusercontent.com/2158203/54060323-98a49e00-41fc-11e9-8eab-234aca8fc4d0.png)
  
  the UI says emails will be sent from "orga@event.com", but they are sent from "admin@localhost" (the value in the global `MAIL_FROM`).
  
  ## Expected Behavior
  
  the sender should be "orga@event.com"
  
  ## Steps to Reproduce
  
  1. create event
  2. set an orga email address `orga@event.com`
  3. do _not_ set a "Sender address" in mail settings, but observe the text below
  4. send email
  5. email is has `From: event <admin@localhost>`, not `From: event <orga@event.com>`
  
  ## Context
  
  <!--- How has this issue affected you? What are you trying to accomplish? -->
  <!--- Providing context helps us come up with a solution that is most useful in the real world -->
  
  ## Your Environment
  
  <!--- Include as many relevant details about the environment you experienced the bug in -->
  * Version used: 5a5ab5482dd9a7a3b19b91563946c535fe5abe1e
  * Environment name and version (e.g. Chrome 39, python 3.5):
  * Operating System and version (desktop or mobile):
  * Link to your instance, if in production:
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `src/pretalx/common/mail.py`
  Content:
  ```
  1 import logging
  2 from email.utils import formataddr
  3 from smtplib import SMTPResponseException, SMTPSenderRefused
  4 from typing import Any, Dict, Union
  5 
  6 from django.conf import settings
  7 from django.core.mail import EmailMultiAlternatives, get_connection
  8 from django.core.mail.backends.smtp import EmailBackend
  9 from django.utils.translation import override
  10 from i18nfield.strings import LazyI18nString
  11 from inlinestyler.utils import inline_css
  12 
  13 from pretalx.celery_app import app
  14 from pretalx.event.models import Event
  15 from pretalx.person.models import User
  16 
  17 logger = logging.getLogger(__name__)
  18 
  19 
  20 class CustomSMTPBackend(EmailBackend):
  21     def test(self, from_addr):
  22         try:
  23             self.open()
  24             self.connection.ehlo_or_helo_if_needed()
  25             (code, resp) = self.connection.mail(from_addr, [])
  26             if code != 250:
  27                 logger.warning(
  28                     f'Error testing mail settings, code {code}, resp: {resp}'
  29                 )
  30                 raise SMTPSenderRefused(code, resp)
  31             (code, resp) = self.connection.rcpt('test@example.com')
  32             if code not in (250, 251):
  33                 logger.warning(
  34                     f'Error testing mail settings, code {code}, resp: {resp}'
  35                 )
  36                 raise SMTPSenderRefused(code, resp)
  37         finally:
  38             self.close()
  39 
  40 
  41 class TolerantDict(dict):
  42     def __missing__(self, key):
  43         """Don't fail when formatting strings with a dict with missing keys."""
  44         return key
  45 
  46 
  47 class SendMailException(Exception):
  48     pass
  49 
  50 
  51 def mail(
  52     user: User,
  53     subject: str,
  54     template: Union[str, LazyI18nString],
  55     context: Dict[str, Any] = None,
  56     event: Event = None,
  57     locale: str = None,
  58     headers: dict = None,
  59 ):
  60     from pretalx.mail.models import QueuedMail
  61 
  62     headers = headers or {}
  63 
  64     with override(locale):
  65         body = str(template)
  66         if context:
  67             body = body.format_map(TolerantDict(context))
  68         reply_to = headers.get('reply-to')
  69         if reply_to and isinstance(reply_to, list):
  70             reply_to = ','.join(reply_to)
  71         QueuedMail(
  72             event=event,
  73             to=user.email,
  74             subject=str(subject),
  75             text=body,
  76             reply_to=reply_to,
  77             bcc=headers.get('bcc'),
  78         ).send()
  79 
  80 
  81 @app.task(bind=True)
  82 def mail_send_task(
  83     self,
  84     to: str,
  85     subject: str,
  86     body: str,
  87     html: str,
  88     reply_to: list = None,
  89     event: int = None,
  90     cc: list = None,
  91     bcc: list = None,
  92     headers: dict = None,
  93 ):
  94     headers = headers or dict()
  95     if event:
  96         event = Event.objects.filter(id=event).first()
  97     if event:
  98         sender = event.settings.get('mail_from')
  99         if sender == 'noreply@example.org' or not sender:
  100             sender = settings.MAIL_FROM
  101         if reply_to:
  102             headers['reply-to'] = reply_to.split(',') if isinstance(reply_to, str) else reply_to
  103         backend = event.get_mail_backend()
  104         sender = formataddr((str(event.name), sender))
  105     else:
  106         sender = formataddr(('pretalx', settings.MAIL_FROM))
  107         backend = get_connection(fail_silently=False)
  108 
  109     email = EmailMultiAlternatives(
  110         subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers
  111     )
  112 
  113     if html is not None:
  114         email.attach_alternative(inline_css(html), 'text/html')
  115 
  116     try:
  117         backend.send_messages([email])
  118     except SMTPResponseException as exception:
  119         # Retry on external problems: Connection issues (101, 111), timeouts (421), filled-up mailboxes (422),
  120         # out of memory (431), network issues (442), another timeout (447), or too many mails sent (452)
  121         if exception.smtp_code in (101, 111, 421, 422, 431, 442, 447, 452):
  122             self.retry(max_retries=5, countdown=2 ** (self.request.retries * 2))
  123         logger.exception('Error sending email')
  124         raise SendMailException('Failed to send an email to {}.'.format(to))
  125     except Exception:
  126         logger.exception('Error sending email')
  127         raise SendMailException('Failed to send an email to {}.'.format(to))
  128
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/src/pretalx/common/mail.py b/src/pretalx/common/mail.py
  --- a/src/pretalx/common/mail.py
  +++ b/src/pretalx/common/mail.py
  @@ -92,14 +92,14 @@
       headers: dict = None,
   ):
       headers = headers or dict()
  +    if reply_to and isinstance(reply_to, str):
  +        reply_to = reply_to.split(',')
       if event:
           event = Event.objects.filter(id=event).first()
       if event:
           sender = event.settings.get('mail_from')
           if sender == 'noreply@example.org' or not sender:
  -            sender = settings.MAIL_FROM
  -        if reply_to:
  -            headers['reply-to'] = reply_to.split(',') if isinstance(reply_to, str) else reply_to
  +            sender = event.email
           backend = event.get_mail_backend()
           sender = formataddr((str(event.name), sender))
       else:
  @@ -107,7 +107,7 @@
           backend = get_connection(fail_silently=False)
   
       email = EmailMultiAlternatives(
  -        subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers
  +        subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers, reply_to=reply_to
       )
   
       if html is not None:
  
verification_info: {"golden_diff": "diff --git a/src/pretalx/common/mail.py b/src/pretalx/common/mail.py\n--- a/src/pretalx/common/mail.py\n+++ b/src/pretalx/common/mail.py\n@@ -92,14 +92,14 @@\n     headers: dict = None,\n ):\n     headers = headers or dict()\n+    if reply_to and isinstance(reply_to, str):\n+        reply_to = reply_to.split(',')\n     if event:\n         event = Event.objects.filter(id=event).first()\n     if event:\n         sender = event.settings.get('mail_from')\n         if sender == 'noreply@example.org' or not sender:\n-            sender = settings.MAIL_FROM\n-        if reply_to:\n-            headers['reply-to'] = reply_to.split(',') if isinstance(reply_to, str) else reply_to\n+            sender = event.email\n         backend = event.get_mail_backend()\n         sender = formataddr((str(event.name), sender))\n     else:\n@@ -107,7 +107,7 @@\n         backend = get_connection(fail_silently=False)\n \n     email = EmailMultiAlternatives(\n-        subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers\n+        subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers, reply_to=reply_to\n     )\n \n     if html is not None:\n", "issue": "email sender address fallback is incorrect\n## Current Behavior\r\n\r\n![image](https://user-images.githubusercontent.com/2158203/54060323-98a49e00-41fc-11e9-8eab-234aca8fc4d0.png)\r\n\r\nthe UI says emails will be sent from \"orga@event.com\", but they are sent from \"admin@localhost\" (the value in the global `MAIL_FROM`).\r\n\r\n## Expected Behavior\r\n\r\nthe sender should be \"orga@event.com\"\r\n\r\n## Steps to Reproduce\r\n\r\n1. create event\r\n2. set an orga email address `orga@event.com`\r\n3. do _not_ set a \"Sender address\" in mail settings, but observe the text below\r\n4. send email\r\n5. email is has `From: event <admin@localhost>`, not `From: event <orga@event.com>`\r\n\r\n## Context\r\n\r\n<!--- How has this issue affected you? What are you trying to accomplish? -->\r\n<!--- Providing context helps us come up with a solution that is most useful in the real world -->\r\n\r\n## Your Environment\r\n\r\n<!--- Include as many relevant details about the environment you experienced the bug in -->\r\n* Version used: 5a5ab5482dd9a7a3b19b91563946c535fe5abe1e\r\n* Environment name and version (e.g. Chrome 39, python 3.5):\r\n* Operating System and version (desktop or mobile):\r\n* Link to your instance, if in production:\r\n\n", "before_files": [{"content": "import logging\nfrom email.utils import formataddr\nfrom smtplib import SMTPResponseException, SMTPSenderRefused\nfrom typing import Any, Dict, Union\n\nfrom django.conf import settings\nfrom django.core.mail import EmailMultiAlternatives, get_connection\nfrom django.core.mail.backends.smtp import EmailBackend\nfrom django.utils.translation import override\nfrom i18nfield.strings import LazyI18nString\nfrom inlinestyler.utils import inline_css\n\nfrom pretalx.celery_app import app\nfrom pretalx.event.models import Event\nfrom pretalx.person.models import User\n\nlogger = logging.getLogger(__name__)\n\n\nclass CustomSMTPBackend(EmailBackend):\n    def test(self, from_addr):\n        try:\n            self.open()\n            self.connection.ehlo_or_helo_if_needed()\n            (code, resp) = self.connection.mail(from_addr, [])\n            if code != 250:\n                logger.warning(\n                    f'Error testing mail settings, code {code}, resp: {resp}'\n                )\n                raise SMTPSenderRefused(code, resp)\n            (code, resp) = self.connection.rcpt('test@example.com')\n            if code not in (250, 251):\n                logger.warning(\n                    f'Error testing mail settings, code {code}, resp: {resp}'\n                )\n                raise SMTPSenderRefused(code, resp)\n        finally:\n            self.close()\n\n\nclass TolerantDict(dict):\n    def __missing__(self, key):\n        \"\"\"Don't fail when formatting strings with a dict with missing keys.\"\"\"\n        return key\n\n\nclass SendMailException(Exception):\n    pass\n\n\ndef mail(\n    user: User,\n    subject: str,\n    template: Union[str, LazyI18nString],\n    context: Dict[str, Any] = None,\n    event: Event = None,\n    locale: str = None,\n    headers: dict = None,\n):\n    from pretalx.mail.models import QueuedMail\n\n    headers = headers or {}\n\n    with override(locale):\n        body = str(template)\n        if context:\n            body = body.format_map(TolerantDict(context))\n        reply_to = headers.get('reply-to')\n        if reply_to and isinstance(reply_to, list):\n            reply_to = ','.join(reply_to)\n        QueuedMail(\n            event=event,\n            to=user.email,\n            subject=str(subject),\n            text=body,\n            reply_to=reply_to,\n            bcc=headers.get('bcc'),\n        ).send()\n\n\n@app.task(bind=True)\ndef mail_send_task(\n    self,\n    to: str,\n    subject: str,\n    body: str,\n    html: str,\n    reply_to: list = None,\n    event: int = None,\n    cc: list = None,\n    bcc: list = None,\n    headers: dict = None,\n):\n    headers = headers or dict()\n    if event:\n        event = Event.objects.filter(id=event).first()\n    if event:\n        sender = event.settings.get('mail_from')\n        if sender == 'noreply@example.org' or not sender:\n            sender = settings.MAIL_FROM\n        if reply_to:\n            headers['reply-to'] = reply_to.split(',') if isinstance(reply_to, str) else reply_to\n        backend = event.get_mail_backend()\n        sender = formataddr((str(event.name), sender))\n    else:\n        sender = formataddr(('pretalx', settings.MAIL_FROM))\n        backend = get_connection(fail_silently=False)\n\n    email = EmailMultiAlternatives(\n        subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers\n    )\n\n    if html is not None:\n        email.attach_alternative(inline_css(html), 'text/html')\n\n    try:\n        backend.send_messages([email])\n    except SMTPResponseException as exception:\n        # Retry on external problems: Connection issues (101, 111), timeouts (421), filled-up mailboxes (422),\n        # out of memory (431), network issues (442), another timeout (447), or too many mails sent (452)\n        if exception.smtp_code in (101, 111, 421, 422, 431, 442, 447, 452):\n            self.retry(max_retries=5, countdown=2 ** (self.request.retries * 2))\n        logger.exception('Error sending email')\n        raise SendMailException('Failed to send an email to {}.'.format(to))\n    except Exception:\n        logger.exception('Error sending email')\n        raise SendMailException('Failed to send an email to {}.'.format(to))\n", "path": "src/pretalx/common/mail.py"}], "after_files": [{"content": "import logging\nfrom email.utils import formataddr\nfrom smtplib import SMTPResponseException, SMTPSenderRefused\nfrom typing import Any, Dict, Union\n\nfrom django.conf import settings\nfrom django.core.mail import EmailMultiAlternatives, get_connection\nfrom django.core.mail.backends.smtp import EmailBackend\nfrom django.utils.translation import override\nfrom i18nfield.strings import LazyI18nString\nfrom inlinestyler.utils import inline_css\n\nfrom pretalx.celery_app import app\nfrom pretalx.event.models import Event\nfrom pretalx.person.models import User\n\nlogger = logging.getLogger(__name__)\n\n\nclass CustomSMTPBackend(EmailBackend):\n    def test(self, from_addr):\n        try:\n            self.open()\n            self.connection.ehlo_or_helo_if_needed()\n            (code, resp) = self.connection.mail(from_addr, [])\n            if code != 250:\n                logger.warning(\n                    f'Error testing mail settings, code {code}, resp: {resp}'\n                )\n                raise SMTPSenderRefused(code, resp)\n            (code, resp) = self.connection.rcpt('test@example.com')\n            if code not in (250, 251):\n                logger.warning(\n                    f'Error testing mail settings, code {code}, resp: {resp}'\n                )\n                raise SMTPSenderRefused(code, resp)\n        finally:\n            self.close()\n\n\nclass TolerantDict(dict):\n    def __missing__(self, key):\n        \"\"\"Don't fail when formatting strings with a dict with missing keys.\"\"\"\n        return key\n\n\nclass SendMailException(Exception):\n    pass\n\n\ndef mail(\n    user: User,\n    subject: str,\n    template: Union[str, LazyI18nString],\n    context: Dict[str, Any] = None,\n    event: Event = None,\n    locale: str = None,\n    headers: dict = None,\n):\n    from pretalx.mail.models import QueuedMail\n\n    headers = headers or {}\n\n    with override(locale):\n        body = str(template)\n        if context:\n            body = body.format_map(TolerantDict(context))\n        reply_to = headers.get('reply-to')\n        if reply_to and isinstance(reply_to, list):\n            reply_to = ','.join(reply_to)\n        QueuedMail(\n            event=event,\n            to=user.email,\n            subject=str(subject),\n            text=body,\n            reply_to=reply_to,\n            bcc=headers.get('bcc'),\n        ).send()\n\n\n@app.task(bind=True)\ndef mail_send_task(\n    self,\n    to: str,\n    subject: str,\n    body: str,\n    html: str,\n    reply_to: list = None,\n    event: int = None,\n    cc: list = None,\n    bcc: list = None,\n    headers: dict = None,\n):\n    headers = headers or dict()\n    if reply_to and isinstance(reply_to, str):\n        reply_to = reply_to.split(',')\n    if event:\n        event = Event.objects.filter(id=event).first()\n    if event:\n        sender = event.settings.get('mail_from')\n        if sender == 'noreply@example.org' or not sender:\n            sender = event.email\n        backend = event.get_mail_backend()\n        sender = formataddr((str(event.name), sender))\n    else:\n        sender = formataddr(('pretalx', settings.MAIL_FROM))\n        backend = get_connection(fail_silently=False)\n\n    email = EmailMultiAlternatives(\n        subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers, reply_to=reply_to\n    )\n\n    if html is not None:\n        email.attach_alternative(inline_css(html), 'text/html')\n\n    try:\n        backend.send_messages([email])\n    except SMTPResponseException as exception:\n        # Retry on external problems: Connection issues (101, 111), timeouts (421), filled-up mailboxes (422),\n        # out of memory (431), network issues (442), another timeout (447), or too many mails sent (452)\n        if exception.smtp_code in (101, 111, 421, 422, 431, 442, 447, 452):\n            self.retry(max_retries=5, countdown=2 ** (self.request.retries * 2))\n        logger.exception('Error sending email')\n        raise SendMailException('Failed to send an email to {}.'.format(to))\n    except Exception:\n        logger.exception('Error sending email')\n        raise SendMailException('Failed to send an email to {}.'.format(to))\n", "path": "src/pretalx/common/mail.py"}]}