Repository: aio-libs/aiosmtpd
Pull request #193 (2020-10-11 00:11:31)

Fix ConnectionResetError when the client disconnected
## What do these changes do?

Added error handling for ConnectionResetError.
This will improve the appearance of long exception messages.

## Are there changes in behavior for the user?

Make sure that handle_exception() is not called when the client is actively disconnected.

## Related issue number

* Make sure that handle_exception() do not called when the client disconnect and cancelled. (issue #127 #162)
This will fix connection lost will print errors ConnectionResetError.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes
- [x] Add a new news in NEWS.rst 


codecov[bot]: # [Codecov](https://codecov.io/gh/aio-libs/aiosmtpd/pull/193?src=pr&el=h1) Report
> Merging [#193](https://codecov.io/gh/aio-libs/aiosmtpd/pull/193?src=pr&el=desc) into [master](https://codecov.io/gh/aio-libs/aiosmtpd/commit/f414dcdc0312c4cf3f3d39deb3ea7d15e89a5334?el=desc) will **not change** coverage.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/aio-libs/aiosmtpd/pull/193/graphs/tree.svg?width=650&height=150&src=pr&token=k9dc7NVG69)](https://codecov.io/gh/aio-libs/aiosmtpd/pull/193?src=pr&el=tree)

```diff
@@            Coverage Diff            @@
##            master      #193   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            5         5           
  Lines          796       798    +2     
  Branches       133       133           
=========================================
+ Hits           796       798    +2     
```


| [Impacted Files](https://codecov.io/gh/aio-libs/aiosmtpd/pull/193?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [aiosmtpd/smtp.py](https://codecov.io/gh/aio-libs/aiosmtpd/pull/193/diff?src=pr&el=tree#diff-YWlvc210cGQvc210cC5weQ==) | `100.00% <100.00%> (ø)` | |

------

[Continue to review full report at Codecov](https://codecov.io/gh/aio-libs/aiosmtpd/pull/193?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/aio-libs/aiosmtpd/pull/193?src=pr&el=footer). Last update [97730f3...11981e1](https://codecov.io/gh/aio-libs/aiosmtpd/pull/193?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).

pepoluan: Hi @wevsty , can you merge/rebase latest master into your branch so I can test it?
wevsty: @pepoluan  
I've done rebase. For now you can test it.
wevsty: @pepoluan 

>     * Section signs "§" got replaced with strange symbols; please revert these

I'm sorry that my editor coding caused some problems. 
The symbol "§" has been fully revert.
>     * Some lines are too long, not passing `tox -e qa`; please fix these.

Long lines I've made changes.

I see that Travis CI is showing a build error on py38.
```
py38-cov run-test: commands[5] | python -m coverage report -m --fail-under=100
Name                     Stmts   Miss Branch BrPart  Cover   Missing
--------------------------------------------------------------------
aiosmtpd/__init__.py         0      0      0      0   100%
aiosmtpd/controller.py      55      0      6      0   100%
aiosmtpd/handlers.py       149      0     50      0   100%
aiosmtpd/lmtp.py            12      0      2      0   100%
aiosmtpd/main.py            89      0     18      0   100%
aiosmtpd/smtp.py           651      1    262      1    99%   246->255, 255
--------------------------------------------------------------------
TOTAL                      956      1    338      1    99%
```
My local test with Python 3.8.5 on ubuntu did not prompt an exception. 
The code comments also indicate that the code should skip the test.
I don't think that should be a problem.
pepoluan: > My local test with Python 3.8.5 on ubuntu did not prompt an exception.
> The codes are as follows
> 
> ```python
>         if self.session.ssl is not None:            # pragma: nomswin
>             # If STARTTLS was issued, return False, because True has no effect
>             # on an SSL transport and raises a warning. Our superclass has no
>             # way of knowing we switched to SSL so it might return True.
>             #
>             # This entire method seems not to be called during any of the
>             # starttls tests on Windows.  I don't really know why, but it
>             # causes these lines to fail coverage, hence the `nomswin` pragma
>             # above.
>             return False
> ```
> 
> According to the code instructions, testing under win may not override.
> However, Travis CI gives the result of the uncovered test, which means that there is some probability that the test will not be covered on Linux as well.
> I don't think it's a problem, But replacing it here with `# pragma: no cover` might be a better choice.

It's kind of a well-known intermittent problem. _Very_ hard to nail down because it's not reproducible on any contributor's workstation. See #190 for example. I experienced it a LOT in #192.

Just close this PR and reopen it (since you're the PR's author, you can do both). That will trigger Travis to run again, hopefully the next time it runs, whatever caused that line to be skipped will not happen.
wevsty: I've refreshed the CI,Now the build has passed.
CLAassistant: [![CLA assistant check](https://cla-assistant.io/pull/badge/not_signed)](https://cla-assistant.io/aio-libs/aiosmtpd?pullRequest=193) <br/>Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our [Contributor License Agreement](https://cla-assistant.io/aio-libs/aiosmtpd?pullRequest=193) before we can accept your contribution.<br/><sub>You have signed the CLA already but the status is still pending? Let us [recheck](https://cla-assistant.io/check/aio-libs/aiosmtpd?pullRequest=193) it.</sub>
pepoluan: Sorry for the radio silence. My bandwidth is a bit full at the moment.

I'll do a test on latest of this PR on my systems later today. If they all pass, I'll bump the version and push. And if pass again by the PR checks, I'll merge.
pepoluan: Test progress:
[ ] Windows 10 (via PyCharm runner): `(ALL)`

pepoluan: After 24h if no objections from the other maintainers, we'll Squash & Merge this PR.


Patch:
diff --git a/LICENSE b/LICENSE
index d645695..e57be73 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,202 +1,13 @@
+Copyright 2014-2020 aio-libs collaboration.
 
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
 
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+   http://www.apache.org/licenses/LICENSE-2.0
 
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
-   APPENDIX: How to apply the Apache License to your work.
-
-      To apply the Apache License to your work, attach the following
-      boilerplate notice, with the fields enclosed by brackets "[]"
-      replaced with your own identifying information. (Don't include
-      the brackets!)  The text should be enclosed in the appropriate
-      comment syntax for the file format. We also recommend that a
-      file or class name and description of purpose be included on the
-      same "printed page" as the copyright notice for easier
-      identification within third-party archives.
-
-   Copyright [yyyy] [name of copyright owner]
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/aiosmtpd/docs/NEWS.rst b/aiosmtpd/docs/NEWS.rst
index 00500ed..54679df 100644
--- a/aiosmtpd/docs/NEWS.rst
+++ b/aiosmtpd/docs/NEWS.rst
@@ -2,6 +2,14 @@
  NEWS for aiosmtpd
 ===================
 
+1.2.3a1 (aiosmtpd-next)
+=======================
+
+Fixed/Improved
+--------------
+* handle_exception() no longer get called when the client disconnected. (Closes #127, #162)
+
+
 1.2.2 (2020-11-08)
 ==================
 
diff --git a/aiosmtpd/docs/handlers.rst b/aiosmtpd/docs/handlers.rst
index 1c4a569..4a99255 100644
--- a/aiosmtpd/docs/handlers.rst
+++ b/aiosmtpd/docs/handlers.rst
@@ -121,6 +121,7 @@ synchronously (i.e. they are **not** coroutines).
     a status string, such as ``'542 Internal server error'``.  If the method
     returns ``None`` or raises an exception, an exception will be logged, and a
     ``500`` code will be returned to the client.
+    **Note:** If client connection losted function will not be called.
 
 
 .. _auth_hooks:
diff --git a/aiosmtpd/smtp.py b/aiosmtpd/smtp.py
index 986316c..54d6cd0 100644
--- a/aiosmtpd/smtp.py
+++ b/aiosmtpd/smtp.py
@@ -24,7 +24,7 @@ from typing import (
 from warnings import warn
 
 
-__version__ = '1.2.2'
+__version__ = '1.2.3a1'
 __ident__ = 'Python SMTP {}'.format(__version__)
 log = logging.getLogger('mail.log')
 
@@ -376,6 +376,10 @@ class SMTP(asyncio.StreamReaderProtocol):
                 log.info('Connection lost during _handle_client()')
                 self._writer.close()
                 raise
+            except ConnectionResetError:
+                log.info('Connection lost during _handle_client()')
+                self._writer.close()
+                raise
             except Exception as error:
                 try:
                     status = await self.handle_exception(error)
diff --git a/housekeep.py b/housekeep.py
new file mode 100644
index 0000000..d2c3993
--- /dev/null
+++ b/housekeep.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python3
+
+import os
+import sys
+import pprint
+import argparse
+
+from pathlib import Path
+
+
+FG_CYAN = "\x1b[1;96m"
+BOLD = "\x1b[1m"
+NORM = "\x1b[0m"
+
+TOX_ENV_NAME = os.environ.get("TOX_ENV_NAME", None)
+
+WORKDIRS = (
+    ".pytest-cache",
+    ".pytest_cache",
+    ".tox",
+    "_dynamic",
+    "aiosmtpd.egg-info",
+    "build",
+    "htmlcov",
+    "prof",
+)
+
+
+# region #### Helper funcs ############################################################
+
+
+def deldir(targ: Path):
+    if not targ.exists():
+        return
+    for i, pp in enumerate(reversed(sorted(targ.rglob("*"))), start=1):
+        if pp.is_symlink():
+            pp.unlink()
+        elif pp.is_file():
+            pp.chmod(0o600)
+            pp.unlink()
+        elif pp.is_dir():
+            pp.chmod(0o700)
+            pp.rmdir()
+        else:
+            raise RuntimeError(f"Don't know how to handle '{pp}'")
+        if (i & 1023) == 0:
+            print(".", end="", flush=True)
+    targ.rmdir()
+
+
+# endregion
+
+
+# region #### Functional blocks #######################################################
+
+
+def dump_env():
+    os.makedirs("_dynamic", exist_ok=True)
+    with open(f"_dynamic/ENV.{TOX_ENV_NAME}", "wt") as fout:
+        pprint.pprint(dict(os.environ), stream=fout)
+
+
+def move_prof():
+    """Move profiling files to per-testenv dirs"""
+    profpath = Path("prof")
+    prof_files = [
+        f
+        for p in ("*.prof", "*.svg")
+        for f in profpath.glob(p)
+    ]
+    if not prof_files:
+        return
+    targpath = profpath / TOX_ENV_NAME
+    os.makedirs(targpath, exist_ok=True)
+    for f in targpath.glob("*"):
+        f.unlink()
+    for f in prof_files:
+        f.rename(targpath / f.name)
+
+
+def pycache_clean(verbose=False):
+    """Cleanup __pycache__ dirs & bytecode files (if any)"""
+    aiosmtpdpath = Path(".")
+    for i, f in enumerate(aiosmtpdpath.rglob("*.py[co]"), start=1):
+        if verbose and (i % 63) == 0:
+            print(".", end="", flush=True)
+        f.unlink()
+    for d in aiosmtpdpath.rglob("__pycache__"):
+        if verbose:
+            print(".", end="", flush=True)
+        d.rmdir()
+    if verbose:
+        print()
+
+
+def rm_work():
+    """Remove work dirs & files. They are .gitignore'd anyways."""
+    print(f"{BOLD}Removing work dirs ... {NORM}", end="")
+    # The reason we list WORKDIRS explicitly is because we don't want to accidentally
+    # bork IDE workdirs such as .idea/ or .vscode/
+    for dd in WORKDIRS:
+        print(dd, end="", flush=True)
+        deldir(Path(dd))
+        print(" ", end="", flush=True)
+    print(f"\n{BOLD}Removing work files ...{NORM}", end="")
+    for fn in (".coverage", "coverage.xml", "diffcov.html"):
+        print(".", end="", flush=True)
+        fp = Path(fn)
+        if fp.exists():
+            fp.unlink()
+    for fp in Path(".").glob("coverage-*.xml"):
+        print(".", end="", flush=True)
+        fp.unlink()
+    for fp in Path(".").glob("diffcov-*.html"):
+        print(".", end="", flush=True)
+        fp.unlink()
+    print()
+
+
+# endregion
+
+
+# region #### Dispatchers #############################################################
+
+
+def dispatch_setup():
+    dump_env()
+
+
+def dispatch_cleanup():
+    move_prof()
+    pycache_clean()
+
+
+def dispatch_superclean():
+    if TOX_ENV_NAME is not None:
+        raise RuntimeError("Do NOT run this inside tox!")
+    print(f"{BOLD}Running pycache cleanup ...{NORM}", end="")
+    pycache_clean(verbose=True)
+    rm_work()
+
+
+# endregion
+
+
+def get_opts(argv):
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "cmd", metavar="CMD", choices=["setup", "cleanup", "superclean"]
+    )
+    return parser.parse_args(argv)
+
+
+def python_interp_details():
+    print(f"{FG_CYAN}Python interpreter details:{NORM}")
+    details = sys.version.splitlines() + sys.executable.splitlines()
+    for ln in details:
+        print(f"    {FG_CYAN}{ln}{NORM}")
+
+
+if __name__ == "__main__":
+    python_interp_details()
+    if os.environ.get("CI") == "true":
+        # All the housekeeping steps are pointless on Travis CI / GitHub Actions;
+        # they build and tear down their VMs everytime anyways.
+        sys.exit(0)
+    opts = get_opts(sys.argv[1:])
+    dispatcher = globals().get(f"dispatch_{opts.cmd}")
+    dispatcher()
diff --git a/tox.ini b/tox.ini
index 138940d..66a16b1 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,11 +1,10 @@
 [tox]
-envlist = {py36,py37,py38,py39}-{cov,nocov,diffcov}, qa, docs
+envlist = qa, docs, py{36,37,38,39}-{nocov,cov,diffcov}
 skip_missing_interpreters = True
 
 [testenv]
 commands =
-    python -c "import sys; print(sys.version); print(sys.executable)"
-    python -c "import os,pprint; os.makedirs('_dynamic', exist_ok=True); pprint.pprint(dict(os.environ), stream=open('_dynamic/ENV."{envname}"', 'wt'))"
+    python housekeep.py setup
     nocov: python -m nose2 -v {posargs}
     cov: python -m coverage run -m nose2
     cov: python -m coverage combine
@@ -15,8 +14,7 @@ commands =
     diffcov: diff-cover coverage.xml --html-report diffcov.html
     diffcov: diff-cover coverage.xml --fail-under=100
     profile: python -m nose2 --profile {posargs}
-    profile: python -c "open('_dynamic/cPROFILE."{envname}"', 'wb').write(open('_dynamic/cPROFILE', 'rb').read())"
-    python -c "import sys; print(sys.version); print(sys.executable)"
+    python housekeep.py cleanup
 #sitepackages = True
 usedevelop = True
 deps =
@@ -33,11 +31,16 @@ setenv =
     py39: INTERP=py39
     pypy3: INTERP=pypy3
     nocov: PYTHONASYNCIODEBUG=1
-    !py39: PY_39=lt
+    py36: PY_36=eq
+    !py36: PY_36=gt
     py39: PY_39=ge
+    !py39: PY_39=lt
     PLATFORM={env:PLATFORM:linux}
 passenv =
     PYTHON*
+    TRAVIS
+    CI
+    GITHUB*
 
 [testenv:qa]
 basepython = python3
@@ -56,5 +59,5 @@ deps:
 [flake8]
 exclude = conf.py
 jobs = 1
-max-line-length = 79
+max-line-length = 88
 ignore = E123, E133, W503, W504


Test patch:
diff --git a/aiosmtpd/tests/test_smtp.py b/aiosmtpd/tests/test_smtp.py
index 84782b7..53aa4ed 100644
--- a/aiosmtpd/tests/test_smtp.py
+++ b/aiosmtpd/tests/test_smtp.py
@@ -175,6 +175,16 @@ class ErroringErrorHandler:
         raise ValueError('ErroringErrorHandler test')
 
 
+class ErroringHandlerConnectionLost:
+    error = None
+
+    async def handle_DATA(self, server, session, envelope):
+        raise ConnectionResetError('ErroringHandlerConnectionLost test')
+
+    async def handle_exception(self, error):
+        self.error = error
+
+
 class UndescribableError(Exception):
     def __str__(self):
         raise Exception()
@@ -1386,6 +1396,35 @@ Testing
                          b'Error: (ValueError) ErroringErrorHandler test')
         self.assertIsInstance(handler.error, ValueError)
 
+    def test_exception_handler_multiple_connections_lost(self):
+        handler = ErroringHandlerConnectionLost()
+        controller = Controller(handler)
+        controller.start()
+        self.addCleanup(controller.stop)
+        with SMTP(controller.hostname, controller.port) as client1:
+            code, response = client1.ehlo('example.com')
+            self.assertEqual(code, 250)
+            with SMTP(controller.hostname, controller.port) as client2:
+                code, response = client2.ehlo('example.com')
+                self.assertEqual(code, 250)
+                with self.assertRaises(SMTPServerDisconnected) as cm:
+                    mail = CRLF.join(['Test', '.', 'mail'])
+                    client2.sendmail(
+                        'anne@example.com',
+                        ['bart@example.com'],
+                        mail)
+                self.assertIsInstance(cm.exception, SMTPServerDisconnected)
+                self.assertEqual(handler.error, None)
+                # At this point connection should be down
+                with self.assertRaises(SMTPServerDisconnected) as cm:
+                    client2.mail("alice@example.com")
+                self.assertEqual(
+                    "please run connect() first",
+                    str(cm.exception))
+            # client1 shouldn't be affected.
+            code, response = client1.mail("alice@example.com")
+            self.assertEqual(code, 250)
+
     def test_exception_handler_undescribable(self):
         handler = UndescribableErrorHandler()
         controller = ErrorController(handler)