diff --git a/src/lib-sieve/plugins/mailbox/tst-mailboxexists.c b/src/lib-sieve/plugins/mailbox/tst-mailboxexists.c
index 53a5941426a11658b5b32bc338153b7f1a78dc82..e0fd33d1d66bc9eeb9c8a727e8c84c9dfc1f13d3 100644
--- a/src/lib-sieve/plugins/mailbox/tst-mailboxexists.c
+++ b/src/lib-sieve/plugins/mailbox/tst-mailboxexists.c
@@ -157,6 +157,17 @@ tst_mailboxexists_test_mailbox(const struct sieve_runtime_env *renv,
 {
 	const struct sieve_execute_env *eenv = renv->exec_env;
 	struct mailbox *box;
+	const char *error;
+
+	/* Check validity of mailbox name */
+	if (!sieve_mailbox_check_name(mailbox, &error)) {
+		sieve_runtime_warning(
+			renv, NULL, "mailboxexists test: "
+			"invalid mailbox name `%s' specified: %s",
+			str_sanitize(mailbox, 256), error);
+		*all_exist_r = FALSE;
+		return SIEVE_EXEC_OK;
+	}
 
 	/* Open the box */
 	box = mailbox_alloc_for_user(eenv->scriptenv->user,
diff --git a/tests/extensions/mailbox/errors.svtest b/tests/extensions/mailbox/errors.svtest
index fcc17c7e8589c8761356085eda7057f91e6352b2..0821f5212203b97158b8f42c8bef8d31d90bc6e4 100644
--- a/tests/extensions/mailbox/errors.svtest
+++ b/tests/extensions/mailbox/errors.svtest
@@ -20,4 +20,21 @@ test "Invalid Syntax" {
 	}
 }
 
+/*
+ * Mailboxexists - bad UTF-8 in mailbox name
+ */
 
+test "Mailboxexists - bad UTF-8 in mailbox name" {
+	if not test_script_compile "errors/mailboxexists-bad-utf8.sieve" {
+		test_fail "compile failed";
+	}
+
+	if not test_script_run {
+		test_fail "execution failed";
+	}
+
+	# FIXME: check warnings
+	if not test_error :count "eq" :comparator "i;ascii-numeric" "0" {
+		test_fail "wrong number of runtime errors reported";
+	}
+}
diff --git a/tests/extensions/mailbox/errors/mailboxexists-bad-utf8.sieve b/tests/extensions/mailbox/errors/mailboxexists-bad-utf8.sieve
new file mode 100644
index 0000000000000000000000000000000000000000..e68e00e3254868beb84879635f04bbe185e1fce6
--- /dev/null
+++ b/tests/extensions/mailbox/errors/mailboxexists-bad-utf8.sieve
@@ -0,0 +1,9 @@
+require "mailbox";
+require "variables";
+require "encoded-character";
+
+set "mailbox" "${hex:ff}rop";
+if mailboxexists "${mailbox}" {
+	keep;
+}
+