diff --git a/lib/moodlelib.php b/lib/moodlelib.php
index c068e0e1d98..818c7c471be 100644
--- a/lib/moodlelib.php
+++ b/lib/moodlelib.php
@@ -6270,7 +6270,7 @@ function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '',
 
             // If the attachment is a full path to a file in the tempdir, use it as is,
             // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
-            if (strpos($attachpath, $temppath) !== 0) {
+            if ((strpos($attachpath, $temppath) !== 0) && (strpos($attachmentpath, $CFG->dataroot) !== 0)) {
                 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
             }
 
