diff --git a/CHANGES.md b/CHANGES.md
index 33fd946a260dbb92c3c1fce8a35a835f03bf7e56..685ae54abd972fc760cb853c8982f4feeaa9c994 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -4,6 +4,10 @@ moodle-auth_ldap_syncplus
 Changes
 -------
 
+### Unreleased
+
+* 2018-02-07 - Bugfix: Login via email for first-time LDAP logins did not work if multiple LDAP contexts were configured; Credits to derhelge.
+
 ### v3.4-r2
 
 * 2018-02-07 - Add forgotten sync_roles task definition
diff --git a/auth.php b/auth.php
index 475d20c379dc062b96b4708cedd606f496b097cf..ea88f5eebca0812c117c21af1dee69ca9093ab46 100644
--- a/auth.php
+++ b/auth.php
@@ -517,8 +517,8 @@ class auth_plugin_ldap_syncplus extends auth_plugin_ldap {
                 $ldapresult = ldap_list($ldapconnection, $context, $filter, array($authplugin->config->user_attribute));
             }
 
-            // If there is no LDAP result, continue with next context.
-            if (!$ldapresult) {
+            // If there is no LDAP result or if the user was not found in this context, continue with next context.
+            if (!$ldapresult || ldap_count_entries($ldapconnection, $ldapresult) == 0) {
                 continue;
             }