diff --git a/lib/email/receiver.rb b/lib/email/receiver.rb index 6cb0adf8eb2..2510aa1e005 100644 --- a/lib/email/receiver.rb +++ b/lib/email/receiver.rb @@ -756,7 +756,13 @@ module Email def delete_staged_users @staged_users.each do |user| - UserDestroyer.new(Discourse.system_user).destroy(user, quiet: true) if user.posts.count == 0 + if @incoming_email.user.id == user.id + @incoming_email.update_columns(user_id: nil) + end + + if user.posts.count == 0 + UserDestroyer.new(Discourse.system_user).destroy(user, quiet: true) + end end end end diff --git a/spec/components/email/receiver_spec.rb b/spec/components/email/receiver_spec.rb index 69338c3b16a..0054712aa4f 100644 --- a/spec/components/email/receiver_spec.rb +++ b/spec/components/email/receiver_spec.rb @@ -760,6 +760,11 @@ describe Email::Receiver do end end + it "does not remove the incoming email record when staged users are deleted" do + expect { process(:bad_destinations) }.to change { IncomingEmail.count } + .and raise_error(Email::Receiver::BadDestinationAddress) + expect(IncomingEmail.last.message_id).to eq("9@foo.bar.mail") + end end end