You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@james.apache.org by bt...@apache.org on 2022/08/23 01:12:09 UTC

[james-project] 02/02: JAMES-3797 Moving all source code related to SpamAssassin to module third-party/spamassassin

This is an automated email from the ASF dual-hosted git repository.

btellier pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 1618018c413f7ec6ec452baca995ab153af1f17d
Author: Tung Van TRAN <vt...@linagora.com>
AuthorDate: Mon Aug 8 08:20:16 2022 +0700

    JAMES-3797 Moving all source code related to SpamAssassin to module third-party/spamassassin
---
 pom.xml                                            |   5 -
 .../sample-configuration/listeners.xml             |   4 -
 .../src/test/resources/spamassassin.properties     |   2 -
 .../sample-configuration/listeners.xml             |   4 -
 .../sample-configuration/listeners.xml             |   4 -
 .../memory-app/sample-configuration/listeners.xml  |   4 -
 .../memory-app/src/test/resources/listeners.xml    |   3 -
 .../src/test/resources/listeners.xml               |   3 -
 .../spring-app/src/main/resources/smtpserver.xml   |  12 +-
 .../james/transport/matchers/IsMarkedAsSpam.java   |   7 +-
 .../jmap-draft-integration-testing-common/pom.xml  |   5 -
 .../memory-jmap-draft-integration-testing/pom.xml  |   5 -
 .../src/test/resources/listeners.xml               |   3 -
 .../src/test/resources/listeners.xml               |   3 -
 .../java/org/apache/james/util/docker/Images.java  |   1 -
 third-party/spamassassin/docker-compose.yml        |  32 +
 third-party/spamassassin/pom.xml                   | 107 +++-
 .../sample-configuration/extensions.properties     |   1 +
 .../spamassassin/sample-configuration/keystore     | Bin 0 -> 2711 bytes
 .../sample-configuration/listeners.xml             |  26 +
 .../sample-configuration/mailetcontainer.xml       | 167 +++++
 .../sample-configuration/smtpserver.xml            | 158 +++++
 .../sample-configuration}/spamassassin.properties  |   2 +-
 .../apache/james/spamassassin/SpamAssassin.java    | 102 +++
 .../spamassassin/SpamAssassinConfiguration.java    |  57 +-
 .../james/spamassassin}/SpamAssassinHandler.java   |  55 +-
 .../james/spamassassin/SpamAssassinLearner.java    |  56 ++
 .../james/spamassassin/SpamAssassinListener.java   | 185 ++++++
 .../james/spamassassin/SpamAssassinModule.java     |  50 ++
 .../james/spamassassin/MemorySpamAssassinTest.java |  89 +++
 .../SpamAssassinConfigurationTest.java             |  38 +-
 .../james/spamassassin/SpamAssassinContract.java   | 701 +++++++++++++++++++++
 .../spamassassin}/SpamAssassinHandlerTest.java     |  36 +-
 .../spamassassin/SpamAssassinIntegrationTest.java  | 211 +++++++
 .../spamassassin/SpamAssassinListenerTest.java     | 285 +++++++++
 .../james/spamassassin/SpamAssassinTest.java       | 158 +++++
 .../module/SpamAssassinModuleExtension.java        |  65 ++
 .../module/SpamAssassinTestModule.java             |  60 ++
 .../test/resources/docker/spamassassin/spamd.sh    |   2 +-
 .../spamassassin}/src/test/resources/listeners.xml |   2 +-
 .../src/test/resources/mailetcontainer.xml         | 133 ++++
 .../spamassassin/src/test/resources/smtpserver.xml |  54 ++
 42 files changed, 2743 insertions(+), 154 deletions(-)

diff --git a/pom.xml b/pom.xml
index 4667970ad5..9d7cb0d715 100644
--- a/pom.xml
+++ b/pom.xml
@@ -853,11 +853,6 @@
                 <version>${project.version}</version>
                 <type>test-jar</type>
             </dependency>
-            <dependency>
-                <groupId>${james.groupId}</groupId>
-                <artifactId>apache-james-mailbox-spamassassin</artifactId>
-                <version>${project.version}</version>
-            </dependency>
             <dependency>
                 <groupId>${james.groupId}</groupId>
                 <artifactId>apache-james-mailbox-spring</artifactId>
diff --git a/server/apps/cassandra-app/sample-configuration/listeners.xml b/server/apps/cassandra-app/sample-configuration/listeners.xml
index 948cb92031..6a1d26196f 100644
--- a/server/apps/cassandra-app/sample-configuration/listeners.xml
+++ b/server/apps/cassandra-app/sample-configuration/listeners.xml
@@ -21,10 +21,6 @@
 <!-- Read https://james.apache.org/server/config-listeners.html for further details -->
 
 <listeners>
-  <listener>
-    <class>org.apache.james.mailbox.spamassassin.SpamAssassinListener</class>
-    <async>true</async>
-  </listener>
   <listener>
     <class>org.apache.james.mailbox.cassandra.MailboxOperationLoggingListener</class>
   </listener>
diff --git a/server/apps/cassandra-app/src/test/resources/spamassassin.properties b/server/apps/cassandra-app/src/test/resources/spamassassin.properties
deleted file mode 100644
index 134ed31a97..0000000000
--- a/server/apps/cassandra-app/src/test/resources/spamassassin.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-spamassassin.host=localhost
-spamassassin.host=783
\ No newline at end of file
diff --git a/server/apps/distributed-app/sample-configuration/listeners.xml b/server/apps/distributed-app/sample-configuration/listeners.xml
index 758c823704..f039b355a7 100644
--- a/server/apps/distributed-app/sample-configuration/listeners.xml
+++ b/server/apps/distributed-app/sample-configuration/listeners.xml
@@ -22,10 +22,6 @@
 
 <listeners>
   <executeGroupListeners>true</executeGroupListeners>
-  <listener>
-    <class>org.apache.james.mailbox.spamassassin.SpamAssassinListener</class>
-    <async>true</async>
-  </listener>
   <listener>
     <class>org.apache.james.mailbox.cassandra.MailboxOperationLoggingListener</class>
   </listener>
diff --git a/server/apps/distributed-pop3-app/sample-configuration/listeners.xml b/server/apps/distributed-pop3-app/sample-configuration/listeners.xml
index 758c823704..f039b355a7 100644
--- a/server/apps/distributed-pop3-app/sample-configuration/listeners.xml
+++ b/server/apps/distributed-pop3-app/sample-configuration/listeners.xml
@@ -22,10 +22,6 @@
 
 <listeners>
   <executeGroupListeners>true</executeGroupListeners>
-  <listener>
-    <class>org.apache.james.mailbox.spamassassin.SpamAssassinListener</class>
-    <async>true</async>
-  </listener>
   <listener>
     <class>org.apache.james.mailbox.cassandra.MailboxOperationLoggingListener</class>
   </listener>
diff --git a/server/apps/memory-app/sample-configuration/listeners.xml b/server/apps/memory-app/sample-configuration/listeners.xml
index 2eed88076c..41a4383c8d 100644
--- a/server/apps/memory-app/sample-configuration/listeners.xml
+++ b/server/apps/memory-app/sample-configuration/listeners.xml
@@ -21,10 +21,6 @@
 <!-- Read https://james.apache.org/server/config-listeners.html for further details -->
 
 <listeners>
-  <listener>
-    <class>org.apache.james.mailbox.spamassassin.SpamAssassinListener</class>
-    <async>true</async>
-  </listener>
   <preDeletionHook>
     <class>org.apache.james.vault.DeletedMessageVaultHook</class>
   </preDeletionHook>
diff --git a/server/apps/memory-app/src/test/resources/listeners.xml b/server/apps/memory-app/src/test/resources/listeners.xml
index 64f0770525..ae5937f1fa 100644
--- a/server/apps/memory-app/src/test/resources/listeners.xml
+++ b/server/apps/memory-app/src/test/resources/listeners.xml
@@ -19,7 +19,4 @@
  -->
 
 <listeners>
-  <listener>
-    <class>org.apache.james.mailbox.spamassassin.SpamAssassinListener</class>
-  </listener>
 </listeners>
\ No newline at end of file
diff --git a/server/apps/scaling-pulsar-smtp/src/test/resources/listeners.xml b/server/apps/scaling-pulsar-smtp/src/test/resources/listeners.xml
index eabdb5e112..71dccb1ccb 100644
--- a/server/apps/scaling-pulsar-smtp/src/test/resources/listeners.xml
+++ b/server/apps/scaling-pulsar-smtp/src/test/resources/listeners.xml
@@ -19,9 +19,6 @@
  -->
 
 <listeners>
-  <listener>
-    <class>org.apache.james.mailbox.spamassassin.SpamAssassinListener</class>
-  </listener>
   <listener>
     <class>org.apache.james.mailbox.cassandra.MailboxOperationLoggingListener</class>
   </listener>
diff --git a/server/apps/spring-app/src/main/resources/smtpserver.xml b/server/apps/spring-app/src/main/resources/smtpserver.xml
index 31765417da..1b618df439 100644
--- a/server/apps/spring-app/src/main/resources/smtpserver.xml
+++ b/server/apps/spring-app/src/main/resources/smtpserver.xml
@@ -277,17 +277,7 @@
             </handler>
              -->
              
-            <!-- This MessageHandler could be used to check message against spamd before -->
-            <!-- accept the email. So its possible to reject a message on smtplevel if a -->
-            <!-- configured hits amount is reached. -->
-            <!--
-            <handler class="org.apache.james.smtpserver.fastfail.SpamAssassinHandler">
-                <spamdHost>127.0.0.1</spamdHost>
-                <spamdPort>783</spamdPort>
-                <spamdRejectionHits>10</spamdRejectionHits>
-            </handler>
-             -->
-     
+
             <!-- This MessageHandler could be used to extract domain out of the message and check -->
             <!-- this domains against uriRbllists. See http://www.surbl.org for more information. -->
             <!-- The message get rejected if a domain matched . -->
diff --git a/server/mailet/mailets/src/main/java/org/apache/james/transport/matchers/IsMarkedAsSpam.java b/server/mailet/mailets/src/main/java/org/apache/james/transport/matchers/IsMarkedAsSpam.java
index a5ef1aac68..98072e88a3 100644
--- a/server/mailet/mailets/src/main/java/org/apache/james/transport/matchers/IsMarkedAsSpam.java
+++ b/server/mailet/mailets/src/main/java/org/apache/james/transport/matchers/IsMarkedAsSpam.java
@@ -26,7 +26,6 @@ import java.util.Optional;
 import javax.mail.MessagingException;
 
 import org.apache.james.core.MailAddress;
-import org.apache.james.spamassassin.SpamAssassinResult;
 import org.apache.mailet.Mail;
 import org.apache.mailet.base.GenericMatcher;
 
@@ -54,7 +53,9 @@ public class IsMarkedAsSpam extends GenericMatcher {
 
     private static final String YES = "yes";
 
-    private String spamStatusHeader = SpamAssassinResult.STATUS_MAIL.asString();
+    public static final String STATUS_MAIL_PACKAGE_DEFAULT = "org.apache.james.spamassassin.status";
+
+    private String spamStatusHeader = STATUS_MAIL_PACKAGE_DEFAULT;
 
     @Override
     public String getMatcherInfo() {
@@ -65,7 +66,7 @@ public class IsMarkedAsSpam extends GenericMatcher {
     public void init() throws MessagingException {
         spamStatusHeader = Optional.ofNullable(getCondition())
             .filter(s -> !s.isEmpty())
-            .orElse(SpamAssassinResult.STATUS_MAIL.asString());
+            .orElse(STATUS_MAIL_PACKAGE_DEFAULT);
     }
 
     @Override
diff --git a/server/protocols/jmap-draft-integration-testing/jmap-draft-integration-testing-common/pom.xml b/server/protocols/jmap-draft-integration-testing/jmap-draft-integration-testing-common/pom.xml
index 5fa8986b93..96fcb9264d 100644
--- a/server/protocols/jmap-draft-integration-testing/jmap-draft-integration-testing-common/pom.xml
+++ b/server/protocols/jmap-draft-integration-testing/jmap-draft-integration-testing-common/pom.xml
@@ -39,11 +39,6 @@
             <type>test-jar</type>
             <scope>test</scope>
         </dependency>
-        <dependency>
-            <groupId>${james.groupId}</groupId>
-            <artifactId>apache-james-mailbox-spamassassin</artifactId>
-            <scope>test</scope>
-        </dependency>
         <dependency>
             <groupId>${james.groupId}</groupId>
             <artifactId>backup</artifactId>
diff --git a/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/pom.xml b/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/pom.xml
index c0d841e38b..a6293dad92 100644
--- a/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/pom.xml
+++ b/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/pom.xml
@@ -45,11 +45,6 @@
             <type>test-jar</type>
             <scope>test</scope>
         </dependency>
-        <dependency>
-            <groupId>${james.groupId}</groupId>
-            <artifactId>apache-james-mailbox-spamassassin</artifactId>
-            <scope>test</scope>
-        </dependency>
         <dependency>
             <groupId>${james.groupId}</groupId>
             <artifactId>apache-mailet-base</artifactId>
diff --git a/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/src/test/resources/listeners.xml b/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/src/test/resources/listeners.xml
index a686755978..a1a139d2f1 100644
--- a/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/src/test/resources/listeners.xml
+++ b/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/src/test/resources/listeners.xml
@@ -43,9 +43,6 @@
       <name>second</name>
     </configuration>
   </listener>
-  <listener>
-    <class>org.apache.james.mailbox.spamassassin.SpamAssassinListener</class>
-  </listener>
   <listener>
     <class>org.apache.james.jmap.event.PopulateEmailQueryViewListener</class>
     <async>true</async>
diff --git a/server/protocols/jmap-draft-integration-testing/rabbitmq-jmap-draft-integration-testing/src/test/resources/listeners.xml b/server/protocols/jmap-draft-integration-testing/rabbitmq-jmap-draft-integration-testing/src/test/resources/listeners.xml
index 43c8b962ac..1ff4055a56 100644
--- a/server/protocols/jmap-draft-integration-testing/rabbitmq-jmap-draft-integration-testing/src/test/resources/listeners.xml
+++ b/server/protocols/jmap-draft-integration-testing/rabbitmq-jmap-draft-integration-testing/src/test/resources/listeners.xml
@@ -46,9 +46,6 @@
       <name>second</name>
     </configuration>
   </listener>
-  <listener>
-    <class>org.apache.james.mailbox.spamassassin.SpamAssassinListener</class>
-  </listener>
   <listener>
     <class>org.apache.james.jmap.event.PopulateEmailQueryViewListener</class>
     <async>true</async>
diff --git a/server/testing/src/main/java/org/apache/james/util/docker/Images.java b/server/testing/src/main/java/org/apache/james/util/docker/Images.java
index 87054f065a..61074e7596 100644
--- a/server/testing/src/main/java/org/apache/james/util/docker/Images.java
+++ b/server/testing/src/main/java/org/apache/james/util/docker/Images.java
@@ -27,6 +27,5 @@ public interface Images {
     String ELASTICSEARCH_7 = "docker.elastic.co/elasticsearch/elasticsearch:7.10.2";
     String OPENSEARCH = "opensearchproject/opensearch:2.1.0";
     String TIKA = "apache/tika:1.28.2";
-    String SPAMASSASSIN = "instantlinux/spamassassin:3.4.6-1";
     String MOCK_SMTP_SERVER = "linagora/mock-smtp-server:0.4";
 }
diff --git a/third-party/spamassassin/docker-compose.yml b/third-party/spamassassin/docker-compose.yml
new file mode 100644
index 0000000000..618806afc1
--- /dev/null
+++ b/third-party/spamassassin/docker-compose.yml
@@ -0,0 +1,32 @@
+version: '3'
+
+services:
+
+  james:
+    depends_on:
+      - spamassassin
+    image: apache/james:memory-latest
+    container_name: james
+    hostname: james.local
+    volumes:
+      - $PWD/target/apache-james-spamassassin-3.8.0-SNAPSHOT-jar-with-dependencies.jar:/root/extensions-jars/james-server-spamassassin.jar
+      - $PWD/sample-configuration/keystore:/root/conf/keystore
+      - $PWD/sample-configuration/extensions.properties:/root/conf/extensions.properties
+      - $PWD/sample-configuration/spamassassin.properties:/root/conf/spamassassin.properties
+      - $PWD/sample-configuration/mailetcontainer.xml:/root/conf/mailetcontainer.xml
+      - $PWD/sample-configuration/listeners.xml:/root/conf/listeners.xml
+      - $PWD/sample-configuration/smtpserver.xml:/root/conf/smtpserver.xml
+    ports:
+      - "80:80"
+      - "25:25"
+      - "110:110"
+      - "143:143"
+      - "465:465"
+      - "587:587"
+      - "993:993"
+      - "8000:8000"
+
+  spamassassin:
+    image: instantlinux/spamassassin:3.4.6-1
+    ports:
+      - "783:783"
\ No newline at end of file
diff --git a/third-party/spamassassin/pom.xml b/third-party/spamassassin/pom.xml
index 8510f370e8..2042349664 100644
--- a/third-party/spamassassin/pom.xml
+++ b/third-party/spamassassin/pom.xml
@@ -1,5 +1,4 @@
 <?xml version="1.0" encoding="UTF-8"?>
-
 <!--
     Licensed to the Apache Software Foundation (ASF) under one
     or more contributor license agreements. See the NOTICE file
@@ -32,14 +31,81 @@
     <description>SpamAssassin Java client and testing utilities</description>
 
     <dependencies>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>apache-james-mailbox-api</artifactId>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>apache-james-mailbox-memory</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>apache-james-mailbox-memory</artifactId>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>apache-james-mailbox-store</artifactId>
+        </dependency>
         <dependency>
             <groupId>${james.groupId}</groupId>
             <artifactId>apache-mailet-api</artifactId>
         </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>apache-mailet-base</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>event-bus-api</artifactId>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>event-bus-in-vm</artifactId>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>${james.groupId}</groupId>
             <artifactId>james-core</artifactId>
         </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>james-server-data-api</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>james-server-data-memory</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>james-server-guice-common</artifactId>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>james-server-guice-configuration</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>james-server-mailets-integration-testing</artifactId>
+            <version>${project.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>${james.groupId}</groupId>
+            <artifactId>james-server-protocols-smtp</artifactId>
+            <version>${project.version}</version>
+        </dependency>
         <dependency>
             <groupId>${james.groupId}</groupId>
             <artifactId>james-server-testing</artifactId>
@@ -59,6 +125,13 @@
             <artifactId>testing-base</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>${james.protocols.groupId}</groupId>
+            <artifactId>protocols-smtp</artifactId>
+            <version>${project.version}</version>
+            <type>test-jar</type>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>com.github.fge</groupId>
             <artifactId>throwing-lambdas</artifactId>
@@ -67,6 +140,10 @@
             <groupId>com.google.guava</groupId>
             <artifactId>guava</artifactId>
         </dependency>
+        <dependency>
+            <groupId>com.google.inject</groupId>
+            <artifactId>guice</artifactId>
+        </dependency>
         <dependency>
             <groupId>com.sun.mail</groupId>
             <artifactId>javax.mail</artifactId>
@@ -79,6 +156,11 @@
             <groupId>org.apache.commons</groupId>
             <artifactId>commons-lang3</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
@@ -89,5 +171,24 @@
             <scope>test</scope>
         </dependency>
     </dependencies>
-
-</project>
\ No newline at end of file
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-assembly-plugin</artifactId>
+                <configuration>
+                    <descriptorRefs>
+                        <descriptorRef>jar-with-dependencies</descriptorRef>
+                    </descriptorRefs>
+                </configuration>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>single</goal>
+                        </goals>
+                        <phase>compile</phase>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+</project>
diff --git a/third-party/spamassassin/sample-configuration/extensions.properties b/third-party/spamassassin/sample-configuration/extensions.properties
new file mode 100644
index 0000000000..255e435b0d
--- /dev/null
+++ b/third-party/spamassassin/sample-configuration/extensions.properties
@@ -0,0 +1 @@
+guice.extension.module=org.apache.james.spamassassin.SpamAssassinModule
\ No newline at end of file
diff --git a/third-party/spamassassin/sample-configuration/keystore b/third-party/spamassassin/sample-configuration/keystore
new file mode 100644
index 0000000000..361cd01f43
Binary files /dev/null and b/third-party/spamassassin/sample-configuration/keystore differ
diff --git a/third-party/spamassassin/sample-configuration/listeners.xml b/third-party/spamassassin/sample-configuration/listeners.xml
new file mode 100644
index 0000000000..28d5e2c7d7
--- /dev/null
+++ b/third-party/spamassassin/sample-configuration/listeners.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you 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.
+ -->
+
+<!-- Read https://james.apache.org/server/config-listeners.html for further details -->
+
+<listeners>
+    <listener>
+        <class>org.apache.james.spamassassin.SpamAssassinListener</class>
+        <async>true</async>
+    </listener>
+</listeners>
\ No newline at end of file
diff --git a/third-party/spamassassin/sample-configuration/mailetcontainer.xml b/third-party/spamassassin/sample-configuration/mailetcontainer.xml
new file mode 100644
index 0000000000..75d7e1d8f0
--- /dev/null
+++ b/third-party/spamassassin/sample-configuration/mailetcontainer.xml
@@ -0,0 +1,167 @@
+<?xml version="1.0"?>
+
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you 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.
+ -->
+
+<!-- Read https://james.apache.org/server/config-mailetcontainer.html for further details -->
+
+<mailetcontainer enableJmx="true">
+
+    <context>
+        <!-- When the domain part of the postmaster mailAddress is missing, the default domain is appended.
+        You can configure it to (for example) <postmaster>postmaster@myDomain.com</postmaster> -->
+        <postmaster>postmaster</postmaster>
+    </context>
+
+    <spooler>
+        <threads>20</threads>
+        <errorRepository>memory://var/mail/error/</errorRepository>
+    </spooler>
+
+    <processors>
+        <processor state="root" enableJmx="true">
+            <mailet match="All" class="PostmasterAlias"/>
+            <mailet match="RelayLimit=30" class="Null"/>
+            <mailet match="All" class="ToProcessor">
+                <processor>transport</processor>
+            </mailet>
+        </processor>
+
+        <processor state="error" enableJmx="true">
+            <mailet match="All" class="MetricsMailet">
+                <metricName>mailetContainerErrors</metricName>
+            </mailet>
+            <mailet match="All" class="Bounce">
+                <onMailetException>ignore</onMailetException>
+            </mailet>
+            <mailet match="All" class="ToRepository">
+                <repositoryPath>memory://var/mail/error/</repositoryPath>
+                <onMailetException>propagate</onMailetException>
+            </mailet>
+        </processor>
+
+        <processor state="transport" enableJmx="true">
+            <matcher name="relay-allowed" match="org.apache.james.mailetcontainer.impl.matchers.Or">
+                <matcher match="SMTPAuthSuccessful"/>
+                <matcher match="SMTPIsAuthNetwork"/>
+                <matcher match="SentByMailet"/>
+                <matcher match="org.apache.james.jmap.mailet.SentByJmap"/>
+            </matcher>
+
+            <mailet match="All" class="RemoveMimeHeader">
+                <name>bcc</name>
+                <onMailetException>ignore</onMailetException>
+            </mailet>
+            <mailet match="All" class="RecipientRewriteTable">
+                <errorProcessor>rrt-error</errorProcessor>
+            </mailet>
+            <mailet match="RecipientIsLocal" class="ToProcessor">
+                <processor>local-delivery</processor>
+            </mailet>
+            <mailet match="HostIsLocal" class="ToProcessor">
+                <processor>local-address-error</processor>
+                <notice>550 - Requested action not taken: no such user here</notice>
+            </mailet>
+            <mailet match="relay-allowed" class="ToProcessor">
+                <processor>relay</processor>
+            </mailet>
+            <mailet match="All" class="ToProcessor">
+                <processor>relay-denied</processor>
+            </mailet>
+        </processor>
+
+        <processor state="local-delivery" enableJmx="true">
+            <mailet match="All" class="org.apache.james.spamassassin.SpamAssassin">
+                <onMailetException>ignore</onMailetException>
+            </mailet>
+            <mailet match="IsMarkedAsSpam" class="WithStorageDirective">
+                <targetFolderName>Spam</targetFolderName>
+            </mailet>
+            <mailet match="All" class="VacationMailet">
+                <onMailetException>ignore</onMailetException>
+            </mailet>
+            <mailet match="All" class="Sieve">
+                <onMailetException>ignore</onMailetException>
+            </mailet>
+            <mailet match="All" class="AddDeliveredToHeader"/>
+            <mailet match="All" class="org.apache.james.jmap.mailet.filter.JMAPFiltering">
+                <onMailetException>ignore</onMailetException>
+            </mailet>
+            <mailet match="All" class="LocalDelivery"/>
+        </processor>
+
+        <processor state="relay" enableJmx="true">
+            <mailet match="All" class="RemoteDelivery">
+                <outgoingQueue>outgoing</outgoingQueue>
+                <delayTime>5000, 100000, 500000</delayTime>
+                <maxRetries>3</maxRetries>
+                <maxDnsProblemRetries>0</maxDnsProblemRetries>
+                <deliveryThreads>10</deliveryThreads>
+                <sendpartial>true</sendpartial>
+                <bounceProcessor>bounces</bounceProcessor>
+            </mailet>
+        </processor>
+
+        <processor state="local-address-error" enableJmx="true">
+            <mailet match="All" class="MetricsMailet">
+                <metricName>mailetContainerLocalAddressError</metricName>
+            </mailet>
+            <mailet match="All" class="Bounce">
+                <attachment>none</attachment>
+            </mailet>
+            <mailet match="All" class="ToRepository">
+                <repositoryPath>memory://var/mail/address-error/</repositoryPath>
+            </mailet>
+        </processor>
+
+        <processor state="relay-denied" enableJmx="true">
+            <mailet match="All" class="MetricsMailet">
+                <metricName>mailetContainerRelayDenied</metricName>
+            </mailet>
+            <mailet match="All" class="Bounce">
+                <attachment>none</attachment>
+            </mailet>
+            <mailet match="All" class="ToRepository">
+                <repositoryPath>memory://var/mail/relay-denied/</repositoryPath>
+                <notice>Warning: You are sending an e-mail to a remote server. You must be authenticated to perform such an operation</notice>
+            </mailet>
+        </processor>
+
+        <processor state="bounces" enableJmx="true">
+            <mailet match="All" class="MetricsMailet">
+                <metricName>bounces</metricName>
+            </mailet>
+            <mailet match="All" class="DSNBounce">
+                <passThrough>false</passThrough>
+            </mailet>
+        </processor>
+
+        <processor state="rrt-error" enableJmx="false">
+            <mailet match="All" class="ToRepository">
+                <repositoryPath>memory://var/mail/rrt-error/</repositoryPath>
+                <passThrough>true</passThrough>
+            </mailet>
+            <mailet match="IsSenderInRRTLoop" class="Null"/>
+            <mailet match="All" class="Bounce"/>
+        </processor>
+
+    </processors>
+
+</mailetcontainer>
+
diff --git a/third-party/spamassassin/sample-configuration/smtpserver.xml b/third-party/spamassassin/sample-configuration/smtpserver.xml
new file mode 100644
index 0000000000..1909b95be1
--- /dev/null
+++ b/third-party/spamassassin/sample-configuration/smtpserver.xml
@@ -0,0 +1,158 @@
+<?xml version="1.0"?>
+
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you 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.
+ -->
+
+<!-- Read https://james.apache.org/server/config-smtp-lmtp.html#SMTP_Configuration for further details -->
+
+<smtpservers>
+    <smtpserver enabled="true">
+        <jmxName>smtpserver-global</jmxName>
+        <bind>0.0.0.0:25</bind>
+        <connectionBacklog>200</connectionBacklog>
+        <tls socketTLS="false" startTLS="false">
+            <!-- To create a new keystore execute:
+              keytool -genkey -alias james -keyalg RSA -storetype PKCS12 -keystore /path/to/james/conf/keystore
+             -->
+            <keystore>file://conf/keystore</keystore>
+            <keystoreType>PKCS12</keystoreType>
+            <secret>james72laBalle</secret>
+            <provider>org.bouncycastle.jce.provider.BouncyCastleProvider</provider>
+            <algorithm>SunX509</algorithm>
+
+            <!-- Alternatively TLS keys can be supplied via PEM files -->
+            <!-- <privateKey>file://conf/private.key</privateKey> -->
+            <!-- <certificates>file://conf/certs.self-signed.csr</certificates> -->
+            <!-- An optional secret might be specified for the private key -->
+            <!-- <secret>james72laBalle</secret> -->
+        </tls>
+        <connectiontimeout>360</connectiontimeout>
+        <connectionLimit>0</connectionLimit>
+        <connectionLimitPerIP>0</connectionLimitPerIP>
+        <auth>
+            <announce>never</announce>
+            <requireSSL>false</requireSSL>
+            <plainAuthEnabled>true</plainAuthEnabled>
+        </auth>
+        <authorizedAddresses>127.0.0.0/8</authorizedAddresses>
+        <verifyIdentity>false</verifyIdentity>
+        <maxmessagesize>0</maxmessagesize>
+        <addressBracketsEnforcement>true</addressBracketsEnforcement>
+        <smtpGreeting>Apache JAMES awesome SMTP Server</smtpGreeting>
+        <handlerchain>
+            <handler class="org.apache.james.smtpserver.fastfail.ValidRcptHandler"/>
+            <handler class="org.apache.james.smtpserver.CoreCmdHandlerLoader"/>
+            <handler class="org.apache.james.spamassassin.SpamAssassinHandler"/>
+        </handlerchain>
+    </smtpserver>
+    <smtpserver enabled="true">
+        <jmxName>smtpserver-TLS</jmxName>
+        <bind>0.0.0.0:465</bind>
+        <connectionBacklog>200</connectionBacklog>
+        <tls socketTLS="true" startTLS="false">
+            <!-- To create a new keystore execute:
+              keytool -genkey -alias james -keyalg RSA -storetype PKCS12 -keystore /path/to/james/conf/keystore
+             -->
+            <keystore>file://conf/keystore</keystore>
+            <keystoreType>PKCS12</keystoreType>
+            <secret>james72laBalle</secret>
+            <provider>org.bouncycastle.jce.provider.BouncyCastleProvider</provider>
+            <algorithm>SunX509</algorithm>
+
+            <!-- Alternatively TLS keys can be supplied via PEM files -->
+            <!-- <privateKey>file://conf/private.key</privateKey> -->
+            <!-- <certificates>file://conf/certs.self-signed.csr</certificates> -->
+            <!-- An optional secret might be specified for the private key -->
+            <!-- <secret>james72laBalle</secret> -->
+        </tls>
+        <connectiontimeout>360</connectiontimeout>
+        <connectionLimit>0</connectionLimit>
+        <connectionLimitPerIP>0</connectionLimitPerIP>
+        <auth>
+            <announce>forUnauthorizedAddresses</announce>
+            <requireSSL>true</requireSSL>
+            <plainAuthEnabled>true</plainAuthEnabled>
+            <oidc>
+                <oidcConfigurationURL>https://auth.upn.integration-open-paas.org/auth/realms/upn/.well-known/openid-configuration</oidcConfigurationURL>
+                <jwksURL>https://auth.upn.integration-open-paas.org/auth/realms/upn/protocol/openid-connect/certs</jwksURL>
+                <claim>email</claim>
+                <scope>openid profile email</scope>
+            </oidc>
+        </auth>
+        <authorizedAddresses>127.0.0.0/8</authorizedAddresses>
+        <!-- Trust authenticated users -->
+        <verifyIdentity>false</verifyIdentity>
+        <maxmessagesize>0</maxmessagesize>
+        <addressBracketsEnforcement>true</addressBracketsEnforcement>
+        <smtpGreeting>Apache JAMES awesome SMTP Server</smtpGreeting>
+        <handlerchain>
+            <handler class="org.apache.james.smtpserver.fastfail.ValidRcptHandler"/>
+            <handler class="org.apache.james.smtpserver.CoreCmdHandlerLoader"/>
+            <handler class="org.apache.james.spamassassin.SpamAssassinHandler"/>
+        </handlerchain>
+    </smtpserver>
+    <smtpserver enabled="true">
+        <jmxName>smtpserver-authenticated</jmxName>
+        <bind>0.0.0.0:587</bind>
+        <connectionBacklog>200</connectionBacklog>
+        <tls socketTLS="false" startTLS="true">
+            <!-- To create a new keystore execute:
+              keytool -genkey -alias james -keyalg RSA -storetype PKCS12 -keystore /path/to/james/conf/keystore
+             -->
+            <keystore>file://conf/keystore</keystore>
+            <keystoreType>PKCS12</keystoreType>
+            <secret>james72laBalle</secret>
+            <provider>org.bouncycastle.jce.provider.BouncyCastleProvider</provider>
+            <algorithm>SunX509</algorithm>
+
+            <!-- Alternatively TLS keys can be supplied via PEM files -->
+            <!-- <privateKey>file://conf/private.key</privateKey> -->
+            <!-- <certificates>file://conf/certs.self-signed.csr</certificates> -->
+            <!-- An optional secret might be specified for the private key -->
+            <!-- <secret>james72laBalle</secret> -->
+        </tls>
+        <connectiontimeout>360</connectiontimeout>
+        <connectionLimit>0</connectionLimit>
+        <connectionLimitPerIP>0</connectionLimitPerIP>
+        <auth>
+            <announce>forUnauthorizedAddresses</announce>
+            <requireSSL>true</requireSSL>
+            <plainAuthEnabled>true</plainAuthEnabled>
+            <oidc>
+                <oidcConfigurationURL>https://auth.upn.integration-open-paas.org/auth/realms/upn/.well-known/openid-configuration</oidcConfigurationURL>
+                <jwksURL>https://auth.upn.integration-open-paas.org/auth/realms/upn/protocol/openid-connect/certs</jwksURL>
+                <claim>email</claim>
+                <scope>openid profile email</scope>
+            </oidc>
+        </auth>
+        <authorizedAddresses>127.0.0.0/8</authorizedAddresses>
+        <!-- Trust authenticated users -->
+        <verifyIdentity>false</verifyIdentity>
+        <maxmessagesize>0</maxmessagesize>
+        <addressBracketsEnforcement>true</addressBracketsEnforcement>
+        <smtpGreeting>Apache JAMES awesome SMTP Server</smtpGreeting>
+        <handlerchain>
+            <handler class="org.apache.james.smtpserver.fastfail.ValidRcptHandler"/>
+            <handler class="org.apache.james.smtpserver.CoreCmdHandlerLoader"/>
+            <handler class="org.apache.james.spamassassin.SpamAssassinHandler"/>
+        </handlerchain>
+    </smtpserver>
+</smtpservers>
+
+
diff --git a/server/apps/memory-app/src/test/resources/spamassassin.properties b/third-party/spamassassin/sample-configuration/spamassassin.properties
similarity index 57%
rename from server/apps/memory-app/src/test/resources/spamassassin.properties
rename to third-party/spamassassin/sample-configuration/spamassassin.properties
index 134ed31a97..99312441dc 100644
--- a/server/apps/memory-app/src/test/resources/spamassassin.properties
+++ b/third-party/spamassassin/sample-configuration/spamassassin.properties
@@ -1,2 +1,2 @@
 spamassassin.host=localhost
-spamassassin.host=783
\ No newline at end of file
+spamassassin.port=783
\ No newline at end of file
diff --git a/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassin.java b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassin.java
new file mode 100644
index 0000000000..892edbe18b
--- /dev/null
+++ b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassin.java
@@ -0,0 +1,102 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin;
+
+import javax.inject.Inject;
+import javax.mail.MessagingException;
+import javax.mail.internet.MimeMessage;
+
+import org.apache.james.core.MailAddress;
+import org.apache.james.metrics.api.MetricFactory;
+import org.apache.james.user.api.UsersRepository;
+import org.apache.james.user.api.UsersRepositoryException;
+import org.apache.james.util.Host;
+import org.apache.mailet.Attribute;
+import org.apache.mailet.Mail;
+import org.apache.mailet.PerRecipientHeaders;
+import org.apache.mailet.base.GenericMailet;
+
+import com.github.fge.lambdas.Throwing;
+
+
+/**
+ * Sends the message through daemonized SpamAssassin (spamd), visit <a
+ * href="http://spamassassin.apache.org/">spamassassin.apache.org/</a> for info
+ * on configuration. The header X-Spam-Status is added to every message, this
+ * contains the score and the threshold score for spam (usually 5.0). If the
+ * message exceeds the threshold, the header X-Spam-Flag will be added with the
+ * value of YES. The default host for spamd is localhost and the default port is
+ * 783.
+ *
+ * <pre>
+ * <code>
+ *  org.apache.james.spamassassin.status - Holds the status
+ *  org.apache.james.spamassassin.flag   - Holds the flag
+ * </code>
+ * </pre>
+ *
+ * Sample Configuration:
+ *
+ * <pre>
+ * &lt;mailet notmatch="SenderHostIsLocal" class="SpamAssassin"&gt;
+ * </pre>
+ */
+public class SpamAssassin extends GenericMailet {
+    private final MetricFactory metricFactory;
+    private final UsersRepository usersRepository;
+
+    private final Host spamAssassinHost;
+
+    @Inject
+    public SpamAssassin(MetricFactory metricFactory, UsersRepository usersRepository, SpamAssassinConfiguration spamAssassinConfiguration) {
+        this.metricFactory = metricFactory;
+        this.usersRepository = usersRepository;
+        this.spamAssassinHost = spamAssassinConfiguration.getHost();
+    }
+
+    @Override
+    public void service(Mail mail) throws MessagingException {
+        MimeMessage message = mail.getMessage();
+
+        // Invoke SpamAssassin connection and scan the message
+        SpamAssassinInvoker sa = new SpamAssassinInvoker(metricFactory, spamAssassinHost.getHostName(), spamAssassinHost.getPort());
+        mail.getRecipients()
+            .forEach(
+                Throwing.consumer((MailAddress recipient) -> querySpamAssassin(mail, message, sa, recipient))
+                    .sneakyThrow());
+    }
+
+    private void querySpamAssassin(Mail mail, MimeMessage message, SpamAssassinInvoker sa, MailAddress recipient) throws MessagingException, UsersRepositoryException {
+        SpamAssassinResult result = sa.scanMail(message, usersRepository.getUsername(recipient));
+
+        // Add headers per recipient to mail object
+        for (Attribute attribute : result.getHeadersAsAttributes()) {
+            mail.addSpecificHeaderForRecipient(PerRecipientHeaders.Header.builder()
+                .name(attribute.getName().asString())
+                .value((String) attribute.getValue().value())
+                .build(), recipient);
+        }
+    }
+
+    @Override
+    public String getMailetInfo() {
+        return "Checks message against SpamAssassin";
+    }
+}
diff --git a/server/testing/src/main/java/org/apache/james/util/docker/Images.java b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinConfiguration.java
similarity index 57%
copy from server/testing/src/main/java/org/apache/james/util/docker/Images.java
copy to third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinConfiguration.java
index 87054f065a..728f6b270e 100644
--- a/server/testing/src/main/java/org/apache/james/util/docker/Images.java
+++ b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinConfiguration.java
@@ -17,16 +17,47 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.james.util.docker;
-
-public interface Images {
-    String FAKE_SMTP = "weave/rest-smtp-sink:latest";
-    String RABBITMQ = "rabbitmq:3.9.18-management";
-    String ELASTICSEARCH_2 = "elasticsearch:2.4.6";
-    String ELASTICSEARCH_6 = "docker.elastic.co/elasticsearch/elasticsearch:6.3.2";
-    String ELASTICSEARCH_7 = "docker.elastic.co/elasticsearch/elasticsearch:7.10.2";
-    String OPENSEARCH = "opensearchproject/opensearch:2.1.0";
-    String TIKA = "apache/tika:1.28.2";
-    String SPAMASSASSIN = "instantlinux/spamassassin:3.4.6-1";
-    String MOCK_SMTP_SERVER = "linagora/mock-smtp-server:0.4";
-}
+package org.apache.james.spamassassin;
+
+
+import java.util.Objects;
+
+import org.apache.james.util.Host;
+
+import com.google.common.base.MoreObjects;
+
+public class SpamAssassinConfiguration {
+
+    private final Host host;
+
+    public SpamAssassinConfiguration(Host host) {
+        this.host = host;
+    }
+
+
+    public Host getHost() {
+        return host;
+    }
+
+    @Override
+    public final boolean equals(Object o) {
+        if (o instanceof SpamAssassinConfiguration) {
+            SpamAssassinConfiguration that = (SpamAssassinConfiguration) o;
+
+            return Objects.equals(this.host, that.host);
+        }
+        return false;
+    }
+
+    @Override
+    public final int hashCode() {
+        return Objects.hash(host);
+    }
+
+    @Override
+    public String toString() {
+        return MoreObjects.toStringHelper(this)
+            .add("host", host)
+            .toString();
+    }
+}
\ No newline at end of file
diff --git a/server/protocols/protocols-smtp/src/main/java/org/apache/james/smtpserver/fastfail/SpamAssassinHandler.java b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinHandler.java
similarity index 79%
rename from server/protocols/protocols-smtp/src/main/java/org/apache/james/smtpserver/fastfail/SpamAssassinHandler.java
rename to third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinHandler.java
index b8ee0a5c93..56c4409172 100644
--- a/server/protocols/protocols-smtp/src/main/java/org/apache/james/smtpserver/fastfail/SpamAssassinHandler.java
+++ b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinHandler.java
@@ -17,14 +17,14 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.james.smtpserver.fastfail;
+package org.apache.james.spamassassin;
+
 
 import javax.inject.Inject;
 import javax.mail.MessagingException;
 import javax.mail.internet.MimeMessage;
 
 import org.apache.commons.configuration2.Configuration;
-import org.apache.commons.configuration2.ex.ConfigurationException;
 import org.apache.james.metrics.api.MetricFactory;
 import org.apache.james.protocols.api.ProtocolSession.State;
 import org.apache.james.protocols.api.handler.ProtocolHandler;
@@ -33,8 +33,6 @@ import org.apache.james.protocols.smtp.dsn.DSNStatus;
 import org.apache.james.protocols.smtp.hook.HookResult;
 import org.apache.james.protocols.smtp.hook.HookReturnCode;
 import org.apache.james.smtpserver.JamesMessageHook;
-import org.apache.james.spamassassin.SpamAssassinInvoker;
-import org.apache.james.spamassassin.SpamAssassinResult;
 import org.apache.mailet.Mail;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -59,8 +57,6 @@ import org.slf4j.LoggerFactory;
  * 
  * <pre>
  * &lt;handler class="org.apache.james.smtpserver.SpamAssassinHandler"&gt;
- *   &lt;spamdHost&gt;localhost&lt;/spamdHost&gt;
- *   &lt;spamdPort&gt;783&lt;/spamdPort&gt; <br>
  *   &lt;spamdRejectionHits&gt;15.0&lt;/spamdRejectionHits&gt;
  *   &lt;checkAuthNetworks&gt;false&lt;/checkAuthNetworks&gt;
  * &lt;/handler&gt;
@@ -72,46 +68,24 @@ public class SpamAssassinHandler implements JamesMessageHook, ProtocolHandler {
     private static final Logger LOGGER = LoggerFactory.getLogger(SpamAssassinHandler.class);
 
     private final MetricFactory metricFactory;
+    private final SpamAssassinConfiguration spamAssassinConfiguration;
 
-    /** The port spamd is listen on */
-    private int spamdPort = 783;
-
-    /** The host spamd is running on */
-    private String spamdHost = "localhost";
-
-    /** The hits on which the message get rejected */
+    /**
+     * The hits on which the message get rejected
+     */
     private double spamdRejectionHits = 0.0;
 
     @Inject
-    public SpamAssassinHandler(MetricFactory metricFactory) {
+    public SpamAssassinHandler(MetricFactory metricFactory, SpamAssassinConfiguration spamAssassinConfiguration) {
         this.metricFactory = metricFactory;
+        this.spamAssassinConfiguration = spamAssassinConfiguration;
     }
 
-    /**
-     * Set the host the spamd daemon is running at
-     * 
-     * @param spamdHost
-     *            The spamdHost
-     */
-    public void setSpamdHost(String spamdHost) {
-        this.spamdHost = spamdHost;
-    }
-
-    /**
-     * Set the port the spamd daemon is listen on
-     * 
-     * @param spamdPort
-     *            the spamdPort
-     */
-    public void setSpamdPort(int spamdPort) {
-        this.spamdPort = spamdPort;
-    }
 
     /**
      * Set the hits on which the message will be rejected.
-     * 
-     * @param spamdRejectionHits
-     *            The hits
+     *
+     * @param spamdRejectionHits The hits
      */
     public void setSpamdRejectionHits(double spamdRejectionHits) {
         this.spamdRejectionHits = spamdRejectionHits;
@@ -120,10 +94,9 @@ public class SpamAssassinHandler implements JamesMessageHook, ProtocolHandler {
 
     @Override
     public HookResult onMessage(SMTPSession session, Mail mail) {
-
         try {
             MimeMessage message = mail.getMessage();
-            SpamAssassinInvoker sa = new SpamAssassinInvoker(metricFactory, spamdHost, spamdPort);
+            SpamAssassinInvoker sa = new SpamAssassinInvoker(metricFactory, spamAssassinConfiguration.getHost().getHostName(), spamAssassinConfiguration.getHost().getPort());
             SpamAssassinResult result = sa.scanMail(message);
 
             // Add the headers
@@ -158,9 +131,7 @@ public class SpamAssassinHandler implements JamesMessageHook, ProtocolHandler {
     }
 
     @Override
-    public void init(Configuration config) throws ConfigurationException {
-        setSpamdHost(config.getString("spamdHost", "localhost"));
-        setSpamdPort(config.getInt("spamdPort", 783));
-        setSpamdRejectionHits(config.getDouble("spamdRejectionHits", 0.0));        
+    public void init(Configuration config) {
+        setSpamdRejectionHits(config.getDouble("spamdRejectionHits", 0.0));
     }
 }
diff --git a/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinLearner.java b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinLearner.java
new file mode 100644
index 0000000000..7355cb146e
--- /dev/null
+++ b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinLearner.java
@@ -0,0 +1,56 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin;
+
+
+import java.io.InputStream;
+import java.util.List;
+
+import javax.inject.Inject;
+
+import org.apache.james.core.Username;
+import org.apache.james.metrics.api.MetricFactory;
+import org.apache.james.util.Host;
+
+import com.github.fge.lambdas.Throwing;
+
+public class SpamAssassinLearner {
+
+    private final MetricFactory metricFactory;
+    private final Host spamAssassinHost;
+
+    @Inject
+    public SpamAssassinLearner(MetricFactory metricFactory, SpamAssassinConfiguration spamAssassinConfiguration) {
+        this.metricFactory = metricFactory;
+        this.spamAssassinHost = spamAssassinConfiguration.getHost();
+    }
+
+    public void learnSpam(List<InputStream> messages, Username username) {
+        SpamAssassinInvoker invoker = new SpamAssassinInvoker(metricFactory, spamAssassinHost.getHostName(), spamAssassinHost.getPort());
+        messages
+            .forEach(Throwing.consumer(message -> invoker.learnAsSpam(message, username)));
+    }
+
+    public void learnHam(List<InputStream> messages, Username username) {
+        SpamAssassinInvoker invoker = new SpamAssassinInvoker(metricFactory, spamAssassinHost.getHostName(), spamAssassinHost.getPort());
+        messages
+            .forEach(Throwing.consumer(message -> invoker.learnAsHam(message, username)));
+    }
+}
diff --git a/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinListener.java b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinListener.java
new file mode 100644
index 0000000000..19a86262df
--- /dev/null
+++ b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinListener.java
@@ -0,0 +1,185 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin;
+
+
+import java.io.InputStream;
+import java.util.List;
+import java.util.stream.Stream;
+
+import javax.inject.Inject;
+
+import org.apache.james.core.Username;
+import org.apache.james.events.Event;
+import org.apache.james.events.Group;
+import org.apache.james.mailbox.MailboxManager;
+import org.apache.james.mailbox.MailboxSession;
+import org.apache.james.mailbox.Role;
+import org.apache.james.mailbox.SystemMailboxesProvider;
+import org.apache.james.mailbox.events.MailboxEvents.Added;
+import org.apache.james.mailbox.events.MessageMoveEvent;
+import org.apache.james.mailbox.exception.MailboxException;
+import org.apache.james.mailbox.model.Mailbox;
+import org.apache.james.mailbox.model.MailboxId;
+import org.apache.james.mailbox.model.MessageRange;
+import org.apache.james.mailbox.store.MailboxSessionMapperFactory;
+import org.apache.james.mailbox.store.event.SpamEventListener;
+import org.apache.james.mailbox.store.mail.MessageMapper;
+import org.apache.james.mailbox.store.mail.model.MailboxMessage;
+import org.apache.james.mailbox.store.mail.model.Message;
+import org.apache.james.util.streams.Iterators;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.github.fge.lambdas.Throwing;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
+
+public class SpamAssassinListener implements SpamEventListener {
+    public static class SpamAssassinListenerGroup extends Group {
+
+    }
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(SpamAssassinListener.class);
+    private static final int LIMIT = 1;
+    private static final Group GROUP = new SpamAssassinListenerGroup();
+
+    private final SpamAssassinLearner spamAssassinLearner;
+    private final SystemMailboxesProvider systemMailboxesProvider;
+    private final MailboxManager mailboxManager;
+    private final MailboxSessionMapperFactory mapperFactory;
+    private final ExecutionMode executionMode;
+
+    @Inject
+    public SpamAssassinListener(SpamAssassinLearner spamAssassinLearner, SystemMailboxesProvider systemMailboxesProvider, MailboxManager mailboxManager, MailboxSessionMapperFactory mapperFactory, ExecutionMode executionMode) {
+        this.spamAssassinLearner = spamAssassinLearner;
+        this.systemMailboxesProvider = systemMailboxesProvider;
+        this.mailboxManager = mailboxManager;
+        this.mapperFactory = mapperFactory;
+        this.executionMode = executionMode;
+    }
+
+    @Override
+    public Group getDefaultGroup() {
+        return GROUP;
+    }
+
+    @Override
+    public ExecutionMode getExecutionMode() {
+        return executionMode;
+    }
+
+    @Override
+    public boolean isHandling(Event event) {
+        return event instanceof MessageMoveEvent || event instanceof Added;
+    }
+
+    @Override
+    public void event(Event event) throws MailboxException {
+        Username username = Username.of(getClass().getCanonicalName());
+        if (event instanceof MessageMoveEvent) {
+            MailboxSession session = mailboxManager.createSystemSession(username);
+            handleMessageMove(event, session, (MessageMoveEvent) event);
+        }
+        if (event instanceof Added) {
+            MailboxSession session = mailboxManager.createSystemSession(username);
+            handleAdded(event, session, (Added) event);
+        }
+    }
+
+    private void handleAdded(Event event, MailboxSession session, Added addedEvent) {
+        if (isAppendedToInbox(addedEvent)) {
+            Mailbox mailbox = mapperFactory.getMailboxMapper(session).findMailboxById(addedEvent.getMailboxId()).block();
+            MessageMapper messageMapper = mapperFactory.getMessageMapper(session);
+
+            List<InputStream> contents = MessageRange.toRanges(addedEvent.getUids())
+                .stream()
+                .flatMap(range -> retrieveMessages(messageMapper, mailbox, range))
+                .map(Throwing.function(MailboxMessage::getFullContent))
+                .collect(ImmutableList.toImmutableList());
+            spamAssassinLearner.learnHam(contents, event.getUsername());
+        }
+    }
+
+    private void handleMessageMove(Event event, MailboxSession session, MessageMoveEvent messageMoveEvent) {
+        if (isMessageMovedToSpamMailbox(messageMoveEvent)) {
+            LOGGER.debug("Spam event detected");
+            ImmutableList<InputStream> messages = retrieveMessages(messageMoveEvent, session);
+            spamAssassinLearner.learnSpam(messages, event.getUsername());
+        }
+        if (isMessageMovedOutOfSpamMailbox(messageMoveEvent)) {
+            ImmutableList<InputStream> messages = retrieveMessages(messageMoveEvent, session);
+            spamAssassinLearner.learnHam(messages, event.getUsername());
+        }
+    }
+
+    private Stream<MailboxMessage> retrieveMessages(MessageMapper messageMapper, Mailbox mailbox, MessageRange range) {
+        try {
+            return Iterators.toStream(messageMapper.findInMailbox(mailbox, range, MessageMapper.FetchType.FULL, LIMIT));
+        } catch (MailboxException e) {
+            LOGGER.warn("Can not retrieve message {} {}", mailbox.getMailboxId(), range.toString(), e);
+            return Stream.empty();
+        }
+    }
+
+    private boolean isAppendedToInbox(Added addedEvent) {
+        try {
+            return systemMailboxesProvider.findMailbox(Role.INBOX, addedEvent.getUsername())
+                .getId().equals(addedEvent.getMailboxId());
+        } catch (MailboxException e) {
+            LOGGER.warn("Could not resolve Inbox mailbox", e);
+            return false;
+        }
+    }
+
+    private ImmutableList<InputStream> retrieveMessages(MessageMoveEvent messageMoveEvent, MailboxSession session) {
+        return mapperFactory.getMessageIdMapper(session)
+            .find(messageMoveEvent.getMessageIds(), MessageMapper.FetchType.FULL)
+            .stream()
+            .map(Throwing.function(Message::getFullContent))
+            .collect(ImmutableList.toImmutableList());
+    }
+
+    @VisibleForTesting
+    boolean isMessageMovedToSpamMailbox(MessageMoveEvent event) {
+        try {
+            MailboxId spamMailboxId = systemMailboxesProvider.findMailbox(Role.SPAM, event.getUsername()).getId();
+
+            return event.getMessageMoves().addedMailboxIds().contains(spamMailboxId);
+        } catch (MailboxException e) {
+            LOGGER.warn("Could not resolve Spam mailbox", e);
+            return false;
+        }
+    }
+
+    @VisibleForTesting
+    boolean isMessageMovedOutOfSpamMailbox(MessageMoveEvent event) {
+        try {
+            MailboxId spamMailboxId = systemMailboxesProvider.findMailbox(Role.SPAM, event.getUsername()).getId();
+            MailboxId trashMailboxId = systemMailboxesProvider.findMailbox(Role.TRASH, event.getUsername()).getId();
+
+            return event.getMessageMoves().removedMailboxIds().contains(spamMailboxId)
+                && !event.getMessageMoves().addedMailboxIds().contains(trashMailboxId);
+        } catch (MailboxException e) {
+            LOGGER.warn("Could not resolve Spam mailbox", e);
+            return false;
+        }
+    }
+}
\ No newline at end of file
diff --git a/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinModule.java b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinModule.java
new file mode 100644
index 0000000000..2ec1dd0ee9
--- /dev/null
+++ b/third-party/spamassassin/src/main/java/org/apache/james/spamassassin/SpamAssassinModule.java
@@ -0,0 +1,50 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin;
+
+import java.io.FileNotFoundException;
+
+import javax.inject.Singleton;
+
+import org.apache.commons.configuration2.Configuration;
+import org.apache.commons.configuration2.ex.ConfigurationException;
+import org.apache.james.util.Host;
+import org.apache.james.utils.PropertiesProvider;
+
+import com.google.inject.AbstractModule;
+import com.google.inject.Provides;
+
+public class SpamAssassinModule extends AbstractModule {
+    private static final String SPAMASSASSIN_HOST = "spamassassin.host";
+    private static final String SPAMASSASSIN_PORT = "spamassassin.port";
+    public static final String DEFAULT_HOST = "127.0.0.1";
+    public static final int DEFAULT_PORT = 783;
+
+    @Provides
+    @Singleton
+    private SpamAssassinConfiguration getSpamAssassinConfiguration(PropertiesProvider propertiesProvider) throws ConfigurationException, FileNotFoundException {
+        Configuration configuration = propertiesProvider.getConfiguration("spamassassin");
+
+        Host host = Host.from(configuration.getString(SPAMASSASSIN_HOST, DEFAULT_HOST),
+            configuration.getInteger(SPAMASSASSIN_PORT, DEFAULT_PORT));
+
+        return new SpamAssassinConfiguration(host);
+    }
+}
diff --git a/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/MemorySpamAssassinTest.java b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/MemorySpamAssassinTest.java
new file mode 100644
index 0000000000..2ebfe2d656
--- /dev/null
+++ b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/MemorySpamAssassinTest.java
@@ -0,0 +1,89 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin;
+
+import static org.apache.james.data.UsersRepositoryModuleChooser.Implementation.DEFAULT;
+
+import org.apache.james.GuiceJamesServer;
+import org.apache.james.JamesServerBuilder;
+import org.apache.james.JamesServerExtension;
+import org.apache.james.MemoryJamesConfiguration;
+import org.apache.james.MemoryJamesServerMain;
+import org.apache.james.junit.categories.Unstable;
+import org.apache.james.modules.TestJMAPServerModule;
+import org.apache.james.spamassassin.module.SpamAssassinModuleExtension;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+class MemorySpamAssassinTest implements SpamAssassinContract {
+    @RegisterExtension
+    static JamesServerExtension testExtension = new JamesServerBuilder<MemoryJamesConfiguration>(tmpDir ->
+        MemoryJamesConfiguration.builder()
+            .workingDirectory(tmpDir)
+            .configurationFromClasspath()
+            .usersRepository(DEFAULT)
+            .build())
+        .extension(new SpamAssassinModuleExtension())
+        .server(configuration -> MemoryJamesServerMain.createServer(configuration)
+            .overrideWith(new TestJMAPServerModule()))
+        .build();
+
+    @Override
+    @Tag(Unstable.TAG)
+    public void spamShouldBeDeliveredInSpamMailboxWhenSameMessageHasAlreadyBeenMovedToSpam(GuiceJamesServer jamesServer, SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        SpamAssassinContract.super.spamShouldBeDeliveredInSpamMailboxWhenSameMessageHasAlreadyBeenMovedToSpam(jamesServer, spamAssassin);
+    }
+
+    @Override
+    @Tag(Unstable.TAG)
+    public void spamShouldBeDeliveredInSpamMailboxOrInboxWhenMultipleRecipientsConfigurations(GuiceJamesServer jamesServer, SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        SpamAssassinContract.super.spamShouldBeDeliveredInSpamMailboxOrInboxWhenMultipleRecipientsConfigurations(jamesServer, spamAssassin);
+    }
+
+    @Override
+    @Tag(Unstable.TAG)
+    public void movingAMailToTrashShouldNotImpactSpamassassinLearning(GuiceJamesServer jamesServer, SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        SpamAssassinContract.super.movingAMailToTrashShouldNotImpactSpamassassinLearning(jamesServer, spamAssassin);
+    }
+
+    @Override
+    @Tag(Unstable.TAG)
+    public void expungingSpamMessageShouldNotImpactSpamAssassinState(GuiceJamesServer jamesServer, SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        SpamAssassinContract.super.expungingSpamMessageShouldNotImpactSpamAssassinState(jamesServer, spamAssassin);
+    }
+
+    @Override
+    @Tag(Unstable.TAG)
+    public void imapMovesToSpamMailboxShouldBeConsideredAsSpam(GuiceJamesServer jamesServer, SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        SpamAssassinContract.super.imapMovesToSpamMailboxShouldBeConsideredAsSpam(jamesServer, spamAssassin);
+    }
+
+    @Override
+    @Tag(Unstable.TAG)
+    public void imapCopiesToSpamMailboxShouldBeConsideredAsSpam(GuiceJamesServer jamesServer, SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        SpamAssassinContract.super.imapCopiesToSpamMailboxShouldBeConsideredAsSpam(jamesServer, spamAssassin);
+    }
+
+    @Override
+    @Tag(Unstable.TAG)
+    public void deletingSpamMessageShouldNotImpactSpamAssassinState(GuiceJamesServer jamesServer, SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        SpamAssassinContract.super.deletingSpamMessageShouldNotImpactSpamAssassinState(jamesServer, spamAssassin);
+    }
+}
\ No newline at end of file
diff --git a/server/testing/src/main/java/org/apache/james/util/docker/Images.java b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinConfigurationTest.java
similarity index 65%
copy from server/testing/src/main/java/org/apache/james/util/docker/Images.java
copy to third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinConfigurationTest.java
index 87054f065a..aa58537e11 100644
--- a/server/testing/src/main/java/org/apache/james/util/docker/Images.java
+++ b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinConfigurationTest.java
@@ -17,16 +17,28 @@
  * under the License.                                           *
  ****************************************************************/
 
-package org.apache.james.util.docker;
-
-public interface Images {
-    String FAKE_SMTP = "weave/rest-smtp-sink:latest";
-    String RABBITMQ = "rabbitmq:3.9.18-management";
-    String ELASTICSEARCH_2 = "elasticsearch:2.4.6";
-    String ELASTICSEARCH_6 = "docker.elastic.co/elasticsearch/elasticsearch:6.3.2";
-    String ELASTICSEARCH_7 = "docker.elastic.co/elasticsearch/elasticsearch:7.10.2";
-    String OPENSEARCH = "opensearchproject/opensearch:2.1.0";
-    String TIKA = "apache/tika:1.28.2";
-    String SPAMASSASSIN = "instantlinux/spamassassin:3.4.6-1";
-    String MOCK_SMTP_SERVER = "linagora/mock-smtp-server:0.4";
-}
+package org.apache.james.spamassassin;
+
+
+import static org.assertj.core.api.Assertions.assertThatCode;
+
+import org.apache.james.util.Host;
+import org.junit.jupiter.api.Test;
+
+import nl.jqno.equalsverifier.EqualsVerifier;
+
+class SpamAssassinConfigurationTest {
+
+    @Test
+    void spamAssassinConfigurationShouldRespectBeanContract() {
+        EqualsVerifier.forClass(SpamAssassinConfiguration.class)
+            .verify();
+    }
+
+
+    @Test
+    void isEnableShouldReturnTrueWhenConfigured() {
+        assertThatCode(() -> new SpamAssassinConfiguration(Host.from("hostname", 1)))
+            .doesNotThrowAnyException();
+    }
+}
\ No newline at end of file
diff --git a/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinContract.java b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinContract.java
new file mode 100644
index 0000000000..082ec998e6
--- /dev/null
+++ b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinContract.java
@@ -0,0 +1,701 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin;
+
+
+import static io.restassured.RestAssured.given;
+import static io.restassured.RestAssured.with;
+import static io.restassured.config.EncoderConfig.encoderConfig;
+import static io.restassured.config.RestAssuredConfig.newConfig;
+import static org.apache.james.jmap.HttpJmapAuthentication.authenticateJamesUser;
+import static org.apache.james.jmap.JMAPTestingConstants.ARGUMENTS;
+import static org.apache.james.jmap.JMAPTestingConstants.LOCALHOST_IP;
+import static org.apache.james.jmap.JMAPTestingConstants.NAME;
+import static org.apache.james.jmap.JMAPTestingConstants.calmlyAwait;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Durations.ONE_MINUTE;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasSize;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.james.GuiceJamesServer;
+import org.apache.james.core.Username;
+import org.apache.james.jmap.AccessToken;
+import org.apache.james.jmap.LocalHostURIBuilder;
+import org.apache.james.jmap.draft.JmapGuiceProbe;
+import org.apache.james.mailbox.Role;
+import org.apache.james.modules.protocols.ImapGuiceProbe;
+import org.apache.james.util.Port;
+import org.apache.james.utils.DataProbeImpl;
+import org.apache.james.utils.SpoolerProbe;
+import org.apache.james.utils.TestIMAPClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import io.restassured.RestAssured;
+import io.restassured.builder.RequestSpecBuilder;
+import io.restassured.http.ContentType;
+import io.restassured.parsing.Parser;
+
+public interface SpamAssassinContract {
+
+    String BOBS_DOMAIN = "spamer.com";
+    String BOB = "bob@" + BOBS_DOMAIN;
+    String BOB_PASSWORD = "bobPassword";
+    String RECIPIENTS_DOMAIN = "angels.org";
+    String ALICE = "alice@" + RECIPIENTS_DOMAIN;
+    String ALICE_PASSWORD = "alicePassword";
+    String PAUL = "paul@" + RECIPIENTS_DOMAIN;
+    String PAUL_PASSWORD = "paulPassword";
+
+    @BeforeEach
+    default void setup(GuiceJamesServer jamesServer) throws Throwable {
+        RestAssured.requestSpecification = new RequestSpecBuilder()
+            .setContentType(ContentType.JSON)
+            .setAccept(ContentType.JSON)
+            .setConfig(newConfig().encoderConfig(encoderConfig().defaultContentCharset(StandardCharsets.UTF_8)))
+            .setPort(jamesServer.getProbe(JmapGuiceProbe.class).getJmapPort().getValue())
+            .build();
+        RestAssured.defaultParser = Parser.JSON;
+
+        jamesServer.getProbe(DataProbeImpl.class)
+            .fluent()
+            .addDomain(BOBS_DOMAIN)
+            .addDomain(RECIPIENTS_DOMAIN)
+            .addUser(BOB, BOB_PASSWORD)
+            .addUser(ALICE, ALICE_PASSWORD)
+            .addUser(PAUL, PAUL_PASSWORD);
+    }
+
+    @AfterEach
+    default void tearDown(SpamAssassinExtension.SpamAssassin spamAssassin, GuiceJamesServer jamesServer) throws Exception {
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer));
+        spamAssassin.clear(ALICE);
+    }
+
+    default AccessToken accessTokenFor(GuiceJamesServer james, String user, String password) {
+        return authenticateJamesUser(baseUri(james), Username.of(user), password);
+    }
+
+    @Test
+    default void spamShouldBeDeliveredInSpamMailboxWhenSameMessageHasAlreadyBeenMovedToSpam(
+        GuiceJamesServer jamesServer,
+        SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+
+        spamAssassin.train(ALICE);
+        AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD);
+        AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD);
+
+        // Bob is sending a message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer));
+
+        // Alice is moving this message to Spam -> learning in SpamAssassin
+        List<String> messageIds = with()
+            .header("Authorization", aliceAccessToken.asString())
+            .body("[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + getInboxId(aliceAccessToken) + "\"]}}, \"#0\"]]")
+            .when()
+            .post("/jmap")
+            .then()
+            .statusCode(200)
+            .body(NAME, equalTo("messageList"))
+            .body(ARGUMENTS + ".messageIds", hasSize(1))
+            .extract()
+            .path(ARGUMENTS + ".messageIds");
+
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"update\": {\"%s\" : { \"mailboxIds\": [\"" + getSpamId(aliceAccessToken) + "\"] } } }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".updated", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+
+        // Bob is sending again the same message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        // This message is delivered in Alice Spam mailbox (she now must have 2 messages in her Spam mailbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 2));
+    }
+
+    @Test
+    default void imapCopiesToSpamMailboxShouldBeConsideredAsSpam(GuiceJamesServer jamesServer,
+                                                                 SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        spamAssassin.train(ALICE);
+        AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD);
+        AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD);
+
+        // Bob is sending a message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer));
+
+
+        // Alice is copying this message to Spam -> learning in SpamAssassin
+        try (TestIMAPClient testIMAPClient = new TestIMAPClient()) {
+            testIMAPClient.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
+                .login(ALICE, ALICE_PASSWORD)
+                .select(TestIMAPClient.INBOX);
+
+            testIMAPClient.copyFirstMessage("Spam");
+        }
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+
+        // Bob is sending again the same message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        // This message is delivered in Alice Spam mailbox (she now must have 2 messages in her Spam mailbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 2));
+    }
+
+    @Test
+    default void imapMovesToSpamMailboxShouldBeConsideredAsSpam(GuiceJamesServer jamesServer,
+                                                                SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        spamAssassin.train(ALICE);
+        AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD);
+        AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD);
+
+        // Bob is sending a message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer));
+
+        try (TestIMAPClient testIMAPClient = new TestIMAPClient()) {
+            testIMAPClient.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
+                .login(ALICE, ALICE_PASSWORD)
+                .select(TestIMAPClient.INBOX);
+
+            testIMAPClient.moveFirstMessage("Spam");
+        }
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+
+        // Bob is sending again the same message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        // This message is delivered in Alice Spam mailbox (she now must have 2 messages in her Spam mailbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 2));
+    }
+
+    @Test
+    default void spamAssassinShouldForgetMessagesMovedOutOfSpamFolderUsingJMAP(GuiceJamesServer jamesServer,
+                                                                               SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        spamAssassin.train(ALICE);
+        AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD);
+        AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD);
+
+        // Bob is sending a message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer));
+
+        // Alice is moving this message to Spam -> learning in SpamAssassin
+        List<String> messageIds = with()
+            .header("Authorization", aliceAccessToken.asString())
+            .body("[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + getInboxId(aliceAccessToken) + "\"]}}, \"#0\"]]")
+            .when()
+            .post("/jmap")
+            .then()
+            .statusCode(200)
+            .body(NAME, equalTo("messageList"))
+            .body(ARGUMENTS + ".messageIds", hasSize(1))
+            .extract()
+            .path(ARGUMENTS + ".messageIds");
+
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"update\": {\"%s\" : { \"mailboxIds\": [\"" + getSpamId(aliceAccessToken) + "\"] } } }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".updated", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+
+        // Alice is moving this message out of Spam -> forgetting in SpamAssassin
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"update\": {\"%s\" : { \"mailboxIds\": [\"" + getInboxId(aliceAccessToken) + "\"] } } }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".updated", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+
+        // Bob is sending again the same message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        // This message is delivered in Alice INBOX mailbox (she now must have 2 messages in her Inbox mailbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 2));
+    }
+
+    @Test
+    default void movingAMailToTrashShouldNotImpactSpamassassinLearning(GuiceJamesServer jamesServer,
+                                                                       SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        spamAssassin.train(ALICE);
+        AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD);
+        AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD);
+
+        // Bob is sending a message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer));
+
+        // Alice is moving this message to Spam -> learning in SpamAssassin
+        List<String> messageIds = with()
+            .header("Authorization", aliceAccessToken.asString())
+            .body("[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + getInboxId(aliceAccessToken) + "\"]}}, \"#0\"]]")
+            .when()
+            .post("/jmap")
+            .then()
+            .statusCode(200)
+            .body(NAME, equalTo("messageList"))
+            .body(ARGUMENTS + ".messageIds", hasSize(1))
+            .extract()
+            .path(ARGUMENTS + ".messageIds");
+
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"update\": {\"%s\" : { \"mailboxIds\": [\"" + getSpamId(aliceAccessToken) + "\"] } } }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".updated", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+
+        // Alice is moving this message to trash
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"update\": {\"%s\" : { \"mailboxIds\": [\"" + getTrashId(aliceAccessToken) + "\"] } } }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".updated", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getTrashId(aliceAccessToken), 1));
+
+        // Bob is sending again the same message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        // This message is delivered in Alice Spam mailbox (she now must have 1 messages in her Spam mailbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+    }
+
+    @Test
+    default void spamAssassinShouldForgetMessagesMovedOutOfSpamFolderUsingIMAP(GuiceJamesServer jamesServer,
+                                                                               SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        spamAssassin.train(ALICE);
+        AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD);
+        AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD);
+
+        // Bob is sending a message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer));
+
+        // Alice is moving this message to Spam -> learning in SpamAssassin
+        List<String> messageIds = with()
+            .header("Authorization", aliceAccessToken.asString())
+            .body("[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + getInboxId(aliceAccessToken) + "\"]}}, \"#0\"]]")
+            .when()
+            .post("/jmap")
+            .then()
+            .statusCode(200)
+            .body(NAME, equalTo("messageList"))
+            .body(ARGUMENTS + ".messageIds", hasSize(1))
+            .extract()
+            .path(ARGUMENTS + ".messageIds");
+
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"update\": {\"%s\" : { \"mailboxIds\": [\"" + getSpamId(aliceAccessToken) + "\"] } } }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".updated", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+
+        // Alice is moving this message out of Spam -> forgetting in SpamAssassin
+        try (TestIMAPClient testIMAPClient = new TestIMAPClient()) {
+            testIMAPClient.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
+                .login(ALICE, ALICE_PASSWORD)
+                .select("Spam");
+
+            testIMAPClient.moveFirstMessage(TestIMAPClient.INBOX);
+        }
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+
+        // Bob is sending again the same message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        // This message is delivered in Alice INBOX mailbox (she now must have 2 messages in her Inbox mailbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 2));
+    }
+
+    @Test
+    default void expungingSpamMessageShouldNotImpactSpamAssassinState(GuiceJamesServer jamesServer,
+                                                                      SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        spamAssassin.train(ALICE);
+        AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD);
+        AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD);
+
+        // Bob is sending a message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer));
+
+        // Alice is moving this message to Spam -> learning in SpamAssassin
+        List<String> messageIds = with()
+            .header("Authorization", aliceAccessToken.asString())
+            .body("[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + getInboxId(aliceAccessToken) + "\"]}}, \"#0\"]]")
+            .when()
+            .post("/jmap")
+            .then()
+            .statusCode(200)
+            .body(NAME, equalTo("messageList"))
+            .body(ARGUMENTS + ".messageIds", hasSize(1))
+            .extract()
+            .path(ARGUMENTS + ".messageIds");
+
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"update\": {\"%s\" : { \"mailboxIds\": [\"" + getSpamId(aliceAccessToken) + "\"] } } }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".updated", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+
+        // Alice is deleting this message
+        try (TestIMAPClient testIMAPClient = new TestIMAPClient()) {
+            testIMAPClient.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
+                .login(ALICE, ALICE_PASSWORD)
+                .select("Spam");
+
+            testIMAPClient.setFlagsForAllMessagesInMailbox("\\Deleted");
+            testIMAPClient.expunge();
+        }
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 0));
+
+        // Bob is sending again the same message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        // This message is delivered in Alice SPAM mailbox (she now must have 1 messages in her Spam mailbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+    }
+
+    @Test
+    default void deletingSpamMessageShouldNotImpactSpamAssassinState(GuiceJamesServer jamesServer,
+                                                                     SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        spamAssassin.train(ALICE);
+        AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD);
+        AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD);
+
+        // Bob is sending a message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertEveryListenerGotCalled(jamesServer));
+
+        // Alice is moving this message to Spam -> learning in SpamAssassin
+        List<String> messageIds = with()
+            .header("Authorization", aliceAccessToken.asString())
+            .body("[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + getInboxId(aliceAccessToken) + "\"]}}, \"#0\"]]")
+            .when()
+            .post("/jmap")
+            .then()
+            .statusCode(200)
+            .body(NAME, equalTo("messageList"))
+            .body(ARGUMENTS + ".messageIds", hasSize(1))
+            .extract()
+            .path(ARGUMENTS + ".messageIds");
+
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"update\": {\"%s\" : { \"mailboxIds\": [\"" + getSpamId(aliceAccessToken) + "\"] } } }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".updated", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+
+        // Alice is deleting this message
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"destroy\": [\"%s\"] }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".destroyed", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 0));
+
+        // Bob is sending again the same message to Alice
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreate(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        // This message is delivered in Alice SPAM mailbox (she now must have 1 messages in her Spam mailbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+    }
+
+    default String setMessageCreate(AccessToken accessToken) {
+        return "[" +
+            "  [" +
+            "    \"setMessages\"," +
+            "    {" +
+            "      \"create\": { \"creationId1337\" : {" +
+            "        \"from\": { \"email\": \"" + BOB + "\"}," +
+            "        \"to\": [{ \"name\": \"recipient\", \"email\": \"" + ALICE + "\"}]," +
+            "        \"subject\": \"Happy News\"," +
+            "        \"textBody\": \"This is a SPAM!!!\r\n\r\n\"," +
+            "        \"mailboxIds\": [\"" + getOutboxId(accessToken) + "\"]" +
+            "      }}" +
+            "    }," +
+            "    \"#0\"" +
+            "  ]" +
+            "]";
+    }
+
+    @Test
+    default void spamShouldBeDeliveredInSpamMailboxOrInboxWhenMultipleRecipientsConfigurations(GuiceJamesServer jamesServer,
+                                                                                               SpamAssassinExtension.SpamAssassin spamAssassin) throws Exception {
+        spamAssassin.train(ALICE);
+        AccessToken aliceAccessToken = accessTokenFor(jamesServer, ALICE, ALICE_PASSWORD);
+        AccessToken bobAccessToken = accessTokenFor(jamesServer, BOB, BOB_PASSWORD);
+        AccessToken paulAccessToken = accessTokenFor(jamesServer, PAUL, PAUL_PASSWORD);
+
+        // Bob is sending a message to Alice & Paul
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreateToMultipleRecipients(bobAccessToken))
+            .when()
+            .post("/jmap");
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 1));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(paulAccessToken, getInboxId(paulAccessToken), 1));
+
+        // Alice is moving this message to Spam -> learning in SpamAssassin
+        List<String> messageIds = with()
+            .header("Authorization", aliceAccessToken.asString())
+            .body("[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + getInboxId(aliceAccessToken) + "\"]}}, \"#0\"]]")
+            .when()
+            .post("/jmap")
+            .then()
+            .statusCode(200)
+            .body(NAME, equalTo("messageList"))
+            .body(ARGUMENTS + ".messageIds", hasSize(1))
+            .extract()
+            .path(ARGUMENTS + ".messageIds");
+
+        messageIds
+            .forEach(messageId -> given()
+                .header("Authorization", aliceAccessToken.asString())
+                .body(String.format("[[\"setMessages\", {\"update\": {\"%s\" : { \"mailboxIds\": [\"" + getSpamId(aliceAccessToken) + "\"] } } }, \"#0\"]]", messageId))
+                .when()
+                .post("/jmap")
+                .then()
+                .statusCode(200)
+                .body(NAME, equalTo("messagesSet"))
+                .body(ARGUMENTS + ".updated", hasSize(1)));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 1));
+
+        // Bob is sending again the same message to Alice & Paul
+        given()
+            .header("Authorization", bobAccessToken.asString())
+            .body(setMessageCreateToMultipleRecipients(bobAccessToken))
+            .when()
+            .post("/jmap");
+
+        // This message is delivered in Alice Spam mailbox (she now must have 2 messages in her Spam mailbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getSpamId(aliceAccessToken), 2));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(aliceAccessToken, getInboxId(aliceAccessToken), 0));
+        // This message is delivered in Paul Inbox (he now must have 2 messages in his Inbox)
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(paulAccessToken, getInboxId(paulAccessToken), 2));
+        calmlyAwait.atMost(ONE_MINUTE).untilAsserted(() -> assertMessagesFoundInMailbox(paulAccessToken, getSpamId(paulAccessToken), 0));
+    }
+
+    default String setMessageCreateToMultipleRecipients(AccessToken accessToken) {
+        return "[" +
+            "  [" +
+            "    \"setMessages\"," +
+            "    {" +
+            "      \"create\": { \"creationId1337\" : {" +
+            "        \"from\": { \"email\": \"" + BOB + "\"}," +
+            "        \"to\": [{ \"name\": \"alice\", \"email\": \"" + ALICE + "\"}, " +
+            "                 { \"name\": \"paul\", \"email\": \"" + PAUL + "\"}]," +
+            "        \"subject\": \"Happy News\"," +
+            "        \"textBody\": \"This is a SPAM!!!\r\n\r\n\"," +
+            "        \"mailboxIds\": [\"" + getOutboxId(accessToken) + "\"]" +
+            "      }}" +
+            "    }," +
+            "    \"#0\"" +
+            "  ]" +
+            "]";
+    }
+
+    default void assertMessagesFoundInMailbox(AccessToken accessToken, String mailboxId, int expectedNumberOfMessages) {
+        with()
+            .header("Authorization", accessToken.asString())
+            .body("[[\"getMessageList\", {\"filter\":{\"inMailboxes\":[\"" + mailboxId + "\"]}}, \"#0\"]]")
+            .when()
+            .post("/jmap")
+            .then()
+            .statusCode(200)
+            .body(NAME, equalTo("messageList"))
+            .body(ARGUMENTS + ".messageIds", hasSize(expectedNumberOfMessages));
+    }
+
+    default String getMailboxId(AccessToken accessToken, Role role) {
+        return getAllMailboxesIds(accessToken).stream()
+            .filter(x -> x.get("role").equalsIgnoreCase(role.serialize()))
+            .map(x -> x.get("id"))
+            .findFirst().get();
+    }
+
+    default List<Map<String, String>> getAllMailboxesIds(AccessToken accessToken) {
+        return with()
+            .header("Authorization", accessToken.asString())
+            .body("[[\"getMailboxes\", {\"properties\": [\"role\", \"id\"]}, \"#0\"]]")
+            .post("/jmap")
+            .andReturn()
+            .body()
+            .jsonPath()
+            .getList(ARGUMENTS + ".list");
+    }
+
+    default String getInboxId(AccessToken accessToken) {
+        return getMailboxId(accessToken, Role.INBOX);
+    }
+
+    default String getOutboxId(AccessToken accessToken) {
+        return getMailboxId(accessToken, Role.OUTBOX);
+    }
+
+    default String getSpamId(AccessToken accessToken) {
+        return getMailboxId(accessToken, Role.SPAM);
+    }
+
+    default String getTrashId(AccessToken accessToken) {
+        return getMailboxId(accessToken, Role.TRASH);
+    }
+
+    default void assertEveryListenerGotCalled(GuiceJamesServer jamesServer) {
+        assertThat(jamesServer.getProbe(SpoolerProbe.class).processingFinished())
+            .describedAs("waiting that every listener get called")
+            .isTrue();
+    }
+
+    private URIBuilder baseUri(GuiceJamesServer jamesServer) {
+        return LocalHostURIBuilder.baseUri(
+            Port.of(jamesServer.getProbe(JmapGuiceProbe.class).getJmapPort().getValue()));
+    }
+}
diff --git a/server/protocols/protocols-smtp/src/test/java/org/apache/james/smtpserver/SpamAssassinHandlerTest.java b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinHandlerTest.java
similarity index 85%
rename from server/protocols/protocols-smtp/src/test/java/org/apache/james/smtpserver/SpamAssassinHandlerTest.java
rename to third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinHandlerTest.java
index 52114261c1..7b976ab0d5 100644
--- a/server/protocols/protocols-smtp/src/test/java/org/apache/james/smtpserver/SpamAssassinHandlerTest.java
+++ b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinHandlerTest.java
@@ -16,7 +16,9 @@
  * specific language governing permissions and limitations      *
  * under the License.                                           *
  ****************************************************************/
-package org.apache.james.smtpserver;
+
+package org.apache.james.spamassassin;
+
 
 import static org.apache.james.spamassassin.SpamAssassinResult.STATUS_MAIL;
 import static org.assertj.core.api.Assertions.assertThat;
@@ -32,14 +34,14 @@ import org.apache.james.core.MailAddress;
 import org.apache.james.core.MaybeSender;
 import org.apache.james.core.builder.MimeMessageBuilder;
 import org.apache.james.metrics.tests.RecordingMetricFactory;
+import org.apache.james.protocols.api.ProtocolSession;
 import org.apache.james.protocols.smtp.SMTPSession;
 import org.apache.james.protocols.smtp.hook.HookResult;
 import org.apache.james.protocols.smtp.hook.HookReturnCode;
 import org.apache.james.protocols.smtp.utils.BaseFakeSMTPSession;
-import org.apache.james.smtpserver.fastfail.SpamAssassinHandler;
-import org.apache.james.spamassassin.SpamAssassinResult;
 import org.apache.james.spamassassin.mock.MockSpamd;
 import org.apache.james.spamassassin.mock.MockSpamdExtension;
+import org.apache.james.util.Host;
 import org.apache.mailet.Attribute;
 import org.apache.mailet.AttributeValue;
 import org.apache.mailet.Mail;
@@ -62,16 +64,16 @@ class SpamAssassinHandlerTest {
 
         return new BaseFakeSMTPSession() {
 
-            private final HashMap<AttachmentKey<?>, Object> sessionState = new HashMap<>();
-            private final HashMap<AttachmentKey<?>, Object> connectionState = new HashMap<>();
+            private final HashMap<ProtocolSession.AttachmentKey<?>, Object> sessionState = new HashMap<>();
+            private final HashMap<ProtocolSession.AttachmentKey<?>, Object> connectionState = new HashMap<>();
             private boolean relayingAllowed;
 
             @Override
-            public <T> Optional<T> setAttachment(AttachmentKey<T> key, T value, State state) {
+            public <T> Optional<T> setAttachment(ProtocolSession.AttachmentKey<T> key, T value, ProtocolSession.State state) {
                 Preconditions.checkNotNull(key, "key cannot be null");
                 Preconditions.checkNotNull(value, "value cannot be null");
 
-                if (state == State.Connection) {
+                if (state == ProtocolSession.State.Connection) {
                     return key.convert(connectionState.put(key, value));
                 } else {
                     return key.convert(sessionState.put(key, value));
@@ -79,10 +81,10 @@ class SpamAssassinHandlerTest {
             }
 
             @Override
-            public <T> Optional<T> removeAttachment(AttachmentKey<T> key, State state) {
+            public <T> Optional<T> removeAttachment(ProtocolSession.AttachmentKey<T> key, ProtocolSession.State state) {
                 Preconditions.checkNotNull(key, "key cannot be null");
 
-                if (state == State.Connection) {
+                if (state == ProtocolSession.State.Connection) {
                     return key.convert(connectionState.remove(key));
                 } else {
                     return key.convert(sessionState.remove(key));
@@ -90,13 +92,13 @@ class SpamAssassinHandlerTest {
             }
 
             @Override
-            public <T> Optional<T> getAttachment(AttachmentKey<T> key, State state) {
+            public <T> Optional<T> getAttachment(ProtocolSession.AttachmentKey<T> key, ProtocolSession.State state) {
                 try {
                     sessionState.put(SMTPSession.SENDER, MaybeSender.of(new MailAddress("sender@james.apache.org")));
                 } catch (AddressException e) {
                     throw new RuntimeException(e);
                 }
-                if (state == State.Connection) {
+                if (state == ProtocolSession.State.Connection) {
                     return key.convert(connectionState.get(key));
                 } else {
                     return key.convert(sessionState.get(key));
@@ -136,10 +138,8 @@ class SpamAssassinHandlerTest {
     void testNonSpam() throws Exception {
         SMTPSession session = setupMockedSMTPSession(setupMockedMail(setupMockedMimeMessage("test")));
 
-        SpamAssassinHandler handler = new SpamAssassinHandler(new RecordingMetricFactory());
+        SpamAssassinHandler handler = new SpamAssassinHandler(new RecordingMetricFactory(), new SpamAssassinConfiguration(Host.from(SPAMD_HOST, spamd.getPort())));
 
-        handler.setSpamdHost(SPAMD_HOST);
-        handler.setSpamdPort(spamd.getPort());
         handler.setSpamdRejectionHits(200.0);
         HookResult response = handler.onMessage(session, mockedMail);
 
@@ -153,10 +153,8 @@ class SpamAssassinHandlerTest {
     void testSpam() throws Exception {
         SMTPSession session = setupMockedSMTPSession(setupMockedMail(setupMockedMimeMessage(MockSpamd.GTUBE)));
 
-        SpamAssassinHandler handler = new SpamAssassinHandler(new RecordingMetricFactory());
+        SpamAssassinHandler handler = new SpamAssassinHandler(new RecordingMetricFactory(), new SpamAssassinConfiguration(Host.from(SPAMD_HOST, spamd.getPort())));
 
-        handler.setSpamdHost(SPAMD_HOST);
-        handler.setSpamdPort(spamd.getPort());
         handler.setSpamdRejectionHits(2000.0);
         HookResult response = handler.onMessage(session, mockedMail);
 
@@ -169,10 +167,8 @@ class SpamAssassinHandlerTest {
     void testSpamReject() throws Exception {
         SMTPSession session = setupMockedSMTPSession(setupMockedMail(setupMockedMimeMessage(MockSpamd.GTUBE)));
 
-        SpamAssassinHandler handler = new SpamAssassinHandler(new RecordingMetricFactory());
+        SpamAssassinHandler handler = new SpamAssassinHandler(new RecordingMetricFactory(), new SpamAssassinConfiguration(Host.from(SPAMD_HOST, spamd.getPort())));
 
-        handler.setSpamdHost(SPAMD_HOST);
-        handler.setSpamdPort(spamd.getPort());
         handler.setSpamdRejectionHits(200.0);
         HookResult response = handler.onMessage(session, mockedMail);
 
diff --git a/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinIntegrationTest.java b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinIntegrationTest.java
new file mode 100644
index 0000000000..2578092b5a
--- /dev/null
+++ b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinIntegrationTest.java
@@ -0,0 +1,211 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin;
+
+import static org.apache.james.MemoryJamesServerMain.SMTP_AND_IMAP_MODULE;
+import static org.apache.james.mailets.configuration.Constants.DEFAULT_DOMAIN;
+import static org.apache.james.mailets.configuration.Constants.FROM;
+import static org.apache.james.mailets.configuration.Constants.LOCALHOST_IP;
+import static org.apache.james.mailets.configuration.Constants.PASSWORD;
+import static org.apache.james.mailets.configuration.Constants.RECIPIENT;
+import static org.apache.james.mailets.configuration.Constants.RECIPIENT2;
+import static org.apache.james.mailets.configuration.Constants.awaitAtMostOneMinute;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.File;
+import java.util.UUID;
+
+import javax.mail.MessagingException;
+
+import org.apache.james.core.builder.MimeMessageBuilder;
+import org.apache.james.mailets.TemporaryJamesServer;
+import org.apache.james.mailets.configuration.CommonProcessors;
+import org.apache.james.mailets.configuration.MailetConfiguration;
+import org.apache.james.mailets.configuration.MailetContainer;
+import org.apache.james.mailets.configuration.ProcessorConfiguration;
+import org.apache.james.modules.protocols.ImapGuiceProbe;
+import org.apache.james.modules.protocols.SmtpGuiceProbe;
+import org.apache.james.transport.matchers.All;
+import org.apache.james.util.Host;
+import org.apache.james.util.docker.DockerContainer;
+import org.apache.james.util.docker.RateLimiters;
+import org.apache.james.utils.DataProbeImpl;
+import org.apache.james.utils.SMTPMessageSender;
+import org.apache.james.utils.TestIMAPClient;
+import org.apache.mailet.base.test.FakeMail;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.io.TempDir;
+import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy;
+
+import com.google.inject.Binder;
+import com.google.inject.Module;
+import com.google.inject.Provides;
+import com.google.inject.Singleton;
+
+class SpamAssassinIntegrationTest {
+    private static final String SPAM_CONTENT = "XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X";
+    private static final String SPAMASSASSIN_IMAGE = "instantlinux/spamassassin:3.4.6-1";
+
+    @RegisterExtension
+    public static DockerContainer spamAssassinContainer = DockerContainer.fromName(SPAMASSASSIN_IMAGE)
+        .withExposedPorts(783)
+        .withAffinityToContainer()
+        .waitingFor(new HostPortWaitStrategy().withRateLimiter(RateLimiters.TWENTIES_PER_SECOND))
+        .withName("james-testing-spamassassin-" + UUID.randomUUID());
+
+    @RegisterExtension
+    public TestIMAPClient messageReader = new TestIMAPClient();
+    @RegisterExtension
+    public SMTPMessageSender messageSender = new SMTPMessageSender(DEFAULT_DOMAIN);
+
+    private TemporaryJamesServer jamesServer;
+
+    @BeforeEach
+    void setup(@TempDir File temporaryFolder) throws Exception {
+        MailetContainer.Builder mailets = TemporaryJamesServer.defaultMailetContainerConfiguration()
+            .putProcessor(
+                ProcessorConfiguration.transport()
+                    .addMailet(MailetConfiguration.builder()
+                        .matcher(All.class)
+                        .mailet(SpamAssassin.class))
+                    .addMailetsFrom(CommonProcessors.deliverOnlyTransport()));
+
+        jamesServer = TemporaryJamesServer.builder()
+            .withBase(SMTP_AND_IMAP_MODULE)
+            .withMailetContainer(mailets)
+            .withOverrides(new Module() {
+                @Override
+                public void configure(Binder binder) {
+                }
+                @Provides
+                @Singleton
+                private SpamAssassinConfiguration provideSpamAssassinConfiguration(){
+                    return new SpamAssassinConfiguration(Host.parseConfString("localhost", spamAssassinContainer.getMappedPort(783)));
+                }
+            })
+            .build(temporaryFolder);
+        jamesServer.start();
+
+        jamesServer.getProbe(DataProbeImpl.class)
+            .fluent()
+            .addDomain(DEFAULT_DOMAIN)
+            .addUser(FROM, PASSWORD)
+            .addUser(RECIPIENT, PASSWORD)
+            .addUser(RECIPIENT2, PASSWORD);
+    }
+
+    @AfterEach
+    void tearDown() {
+        jamesServer.shutdown();
+    }
+
+    @Test
+    void spamAssassinShouldAppendNewHeaderOnMessage() throws Exception {
+        messageSender.connect(LOCALHOST_IP, jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpPort())
+            .authenticate(FROM, PASSWORD)
+            .sendMessage(mailWithContent("This is the content", RECIPIENT));
+
+        messageReader.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
+            .login(RECIPIENT, PASSWORD)
+            .select(TestIMAPClient.INBOX)
+            .awaitMessage(awaitAtMostOneMinute);
+
+        assertThat(messageReader.readFirstMessageHeaders())
+            .contains(
+                SpamAssassinResult.FLAG_MAIL.asString(),
+                SpamAssassinResult.STATUS_MAIL.asString());
+    }
+
+    @Test
+    void spamAssassinShouldAppendNewHeaderWhichDetectIsSpamWhenSpamMessage() throws Exception {
+        messageSender.connect(LOCALHOST_IP, jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpPort())
+            .authenticate(FROM, PASSWORD)
+            .sendMessage(mailWithContent(SPAM_CONTENT, RECIPIENT));
+
+        messageReader.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
+            .login(RECIPIENT, PASSWORD)
+            .select(TestIMAPClient.INBOX)
+            .awaitMessage(awaitAtMostOneMinute);
+
+        String receivedHeaders = messageReader.readFirstMessageHeaders();
+        assertThat(receivedHeaders).contains(SpamAssassinResult.FLAG_MAIL.asString() + ": YES");
+        assertThat(receivedHeaders).contains(SpamAssassinResult.STATUS_MAIL.asString() + ": Yes");
+    }
+
+    @Test
+    void spamAssassinShouldAppendNewHeaderWhichNoWhenNonSpamMessage() throws Exception {
+        messageSender.connect(LOCALHOST_IP, jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpPort())
+            .authenticate(FROM, PASSWORD)
+            .sendMessage(mailWithContent("This is the content", RECIPIENT));
+
+        messageReader.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
+            .login(RECIPIENT, PASSWORD)
+            .select(TestIMAPClient.INBOX)
+            .awaitMessage(awaitAtMostOneMinute);
+
+        String receivedHeaders = messageReader.readFirstMessageHeaders();
+        assertThat(receivedHeaders).contains(SpamAssassinResult.FLAG_MAIL.asString() + ": NO");
+        assertThat(receivedHeaders).contains(SpamAssassinResult.STATUS_MAIL.asString() + ": No");
+    }
+
+    @Test
+    void spamAssassinShouldAppendNewHeaderPerRecipientOnMessage() throws Exception {
+        messageSender.connect(LOCALHOST_IP, jamesServer.getProbe(SmtpGuiceProbe.class).getSmtpPort())
+            .authenticate(FROM, PASSWORD)
+            .sendMessage(mailWithContent("This is the content", RECIPIENT, RECIPIENT2));
+
+        messageReader.connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
+            .login(RECIPIENT, PASSWORD)
+            .select(TestIMAPClient.INBOX)
+            .awaitMessage(awaitAtMostOneMinute);
+
+        assertThat(messageReader.readFirstMessageHeaders())
+            .contains(
+                SpamAssassinResult.FLAG_MAIL.asString(),
+                SpamAssassinResult.STATUS_MAIL.asString());
+
+        messageReader.disconnect()
+            .connect(LOCALHOST_IP, jamesServer.getProbe(ImapGuiceProbe.class).getImapPort())
+            .login(RECIPIENT2, PASSWORD)
+            .select(TestIMAPClient.INBOX)
+            .awaitMessage(awaitAtMostOneMinute);
+
+        assertThat(messageReader.readFirstMessageHeaders())
+            .contains(
+                SpamAssassinResult.FLAG_MAIL.asString(),
+                SpamAssassinResult.STATUS_MAIL.asString());
+    }
+
+    private FakeMail.Builder mailWithContent(String textContent, String... recipients) throws MessagingException {
+        return FakeMail.builder()
+            .name("name")
+            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder()
+                .setSender(FROM)
+                .addToRecipient(recipients)
+                .setSubject("This is the subject")
+                .setText(textContent))
+            .sender(FROM)
+            .recipients(recipients);
+    }
+
+}
diff --git a/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinListenerTest.java b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinListenerTest.java
new file mode 100644
index 0000000000..37dedae991
--- /dev/null
+++ b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinListenerTest.java
@@ -0,0 +1,285 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin;
+
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Date;
+
+import javax.mail.Flags;
+
+import org.apache.james.core.Username;
+import org.apache.james.events.EventListener;
+import org.apache.james.events.Group;
+import org.apache.james.mailbox.DefaultMailboxes;
+import org.apache.james.mailbox.MailboxSession;
+import org.apache.james.mailbox.MailboxSessionUtil;
+import org.apache.james.mailbox.events.MailboxEvents.Added;
+import org.apache.james.mailbox.events.MessageMoveEvent;
+import org.apache.james.mailbox.exception.MailboxException;
+import org.apache.james.mailbox.inmemory.manager.InMemoryIntegrationResources;
+import org.apache.james.mailbox.model.ByteContent;
+import org.apache.james.mailbox.model.Mailbox;
+import org.apache.james.mailbox.model.MailboxId;
+import org.apache.james.mailbox.model.MailboxPath;
+import org.apache.james.mailbox.model.MessageMetaData;
+import org.apache.james.mailbox.model.MessageMoves;
+import org.apache.james.mailbox.model.TestMessageId;
+import org.apache.james.mailbox.model.ThreadId;
+import org.apache.james.mailbox.model.UidValidity;
+import org.apache.james.mailbox.store.MailboxSessionMapperFactory;
+import org.apache.james.mailbox.store.StoreMailboxManager;
+import org.apache.james.mailbox.store.SystemMailboxesProviderImpl;
+import org.apache.james.mailbox.store.event.EventFactory;
+import org.apache.james.mailbox.store.mail.MailboxMapper;
+import org.apache.james.mailbox.store.mail.model.impl.PropertyBuilder;
+import org.apache.james.mailbox.store.mail.model.impl.SimpleMailboxMessage;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class SpamAssassinListenerTest {
+    static final Username USER = Username.of("user");
+    static final MailboxSession MAILBOX_SESSION = MailboxSessionUtil.create(USER);
+    static final UidValidity UID_VALIDITY = UidValidity.of(43);
+    static final TestMessageId MESSAGE_ID = TestMessageId.of(45);
+    static final ThreadId THREAD_ID = ThreadId.fromBaseMessageId(MESSAGE_ID);
+
+    SpamAssassinLearner spamAssassinLearner;
+    SpamAssassinListener listener;
+    Mailbox inbox;
+    Mailbox mailbox1;
+    MailboxId mailboxId1;
+    MailboxId mailboxId2;
+    MailboxId spamMailboxId;
+    MailboxId spamCapitalMailboxId;
+    MailboxId trashMailboxId;
+    MailboxSessionMapperFactory mapperFactory;
+    Mailbox mailbox2;
+
+    @BeforeEach
+    void setup() throws Exception {
+        StoreMailboxManager mailboxManager = spy(InMemoryIntegrationResources.defaultResources().getMailboxManager());
+        SystemMailboxesProviderImpl systemMailboxesProvider = new SystemMailboxesProviderImpl(mailboxManager);
+        when(mailboxManager.createSystemSession(USER))
+            .thenReturn(MAILBOX_SESSION);
+
+        spamAssassinLearner = mock(SpamAssassinLearner.class);
+        mapperFactory = mailboxManager.getMapperFactory();
+        MailboxMapper mailboxMapper = mapperFactory.createMailboxMapper(MAILBOX_SESSION);
+        inbox = mailboxMapper.create(MailboxPath.forUser(USER, DefaultMailboxes.INBOX), UID_VALIDITY).block();
+        mailbox1 = mailboxMapper.create(MailboxPath.forUser(USER, "mailbox1"), UID_VALIDITY).block();
+        mailbox2 = mailboxMapper.create(MailboxPath.forUser(USER, "mailbox2"), UID_VALIDITY).block();
+        mailboxId1 = mailbox1.getMailboxId();
+        mailboxId2 = mailbox2.getMailboxId();
+        spamMailboxId = mailboxMapper.create(MailboxPath.forUser(USER, "Spam"), UID_VALIDITY).block().getMailboxId();
+        spamCapitalMailboxId = mailboxMapper.create(MailboxPath.forUser(USER, "SPAM"), UID_VALIDITY).block().getMailboxId();
+        trashMailboxId = mailboxMapper.create(MailboxPath.forUser(USER, "Trash"), UID_VALIDITY).block().getMailboxId();
+
+        listener = new SpamAssassinListener(spamAssassinLearner, systemMailboxesProvider, mailboxManager, mapperFactory, EventListener.ExecutionMode.SYNCHRONOUS);
+    }
+
+    @Test
+    void deserializeSpamAssassinListenerGroup() throws Exception {
+        assertThat(Group.deserialize("org.apache.james.spamassassin.SpamAssassinListener$SpamAssassinListenerGroup"))
+            .isEqualTo(new SpamAssassinListener.SpamAssassinListenerGroup());
+    }
+
+    @Test
+    void isEventOnSpamMailboxShouldReturnFalseWhenMessageIsMovedToANonSpamMailbox() {
+        MessageMoveEvent messageMoveEvent = MessageMoveEvent.builder()
+            .session(MAILBOX_SESSION)
+            .messageMoves(MessageMoves.builder()
+                .previousMailboxIds(mailboxId1)
+                .targetMailboxIds(mailboxId2)
+                .build())
+            .messageId(MESSAGE_ID)
+            .build();
+
+        assertThat(listener.isMessageMovedToSpamMailbox(messageMoveEvent)).isFalse();
+    }
+
+    @Test
+    void isEventOnSpamMailboxShouldReturnTrueWhenMailboxIsSpam() {
+        MessageMoveEvent messageMoveEvent = MessageMoveEvent.builder()
+            .session(MAILBOX_SESSION)
+            .messageMoves(MessageMoves.builder()
+                .previousMailboxIds(mailboxId1)
+                .targetMailboxIds(spamMailboxId)
+                .build())
+            .messageId(MESSAGE_ID)
+            .build();
+
+        assertThat(listener.isMessageMovedToSpamMailbox(messageMoveEvent)).isTrue();
+    }
+
+    @Test
+    void isEventOnSpamMailboxShouldReturnFalseWhenMailboxIsSpamOtherCase() {
+        MessageMoveEvent messageMoveEvent = MessageMoveEvent.builder()
+            .session(MAILBOX_SESSION)
+            .messageMoves(MessageMoves.builder()
+                .previousMailboxIds(mailboxId1)
+                .targetMailboxIds(spamCapitalMailboxId)
+                .build())
+            .messageId(MESSAGE_ID)
+            .build();
+
+        assertThat(listener.isMessageMovedToSpamMailbox(messageMoveEvent)).isFalse();
+    }
+
+    @Test
+    void eventShouldCallSpamAssassinSpamLearningWhenTheEventMatches() throws Exception {
+        MessageMoveEvent messageMoveEvent = MessageMoveEvent.builder()
+            .session(MAILBOX_SESSION)
+            .messageMoves(MessageMoves.builder()
+                .previousMailboxIds(mailboxId1)
+                .targetMailboxIds(spamMailboxId)
+                .build())
+            .messageId(MESSAGE_ID)
+            .build();
+
+        listener.event(messageMoveEvent);
+
+        verify(spamAssassinLearner).learnSpam(any(), any());
+    }
+
+    @Test
+    void isMessageMovedOutOfSpamMailboxShouldReturnFalseWhenMessageMovedBetweenNonSpamMailboxes() {
+        MessageMoveEvent messageMoveEvent = MessageMoveEvent.builder()
+            .session(MAILBOX_SESSION)
+            .messageMoves(MessageMoves.builder()
+                .previousMailboxIds(mailboxId1)
+                .targetMailboxIds(mailboxId2)
+                .build())
+            .messageId(MESSAGE_ID)
+            .build();
+
+        assertThat(listener.isMessageMovedOutOfSpamMailbox(messageMoveEvent)).isFalse();
+    }
+
+    @Test
+    void isMessageMovedOutOfSpamMailboxShouldReturnFalseWhenMessageMovedOutOfCapitalSpamMailbox() {
+        MessageMoveEvent messageMoveEvent = MessageMoveEvent.builder()
+            .session(MAILBOX_SESSION)
+            .messageMoves(MessageMoves.builder()
+                .previousMailboxIds(spamCapitalMailboxId)
+                .targetMailboxIds(mailboxId2)
+                .build())
+            .messageId(MESSAGE_ID)
+            .build();
+
+        assertThat(listener.isMessageMovedOutOfSpamMailbox(messageMoveEvent)).isFalse();
+    }
+
+    @Test
+    void isMessageMovedOutOfSpamMailboxShouldReturnTrueWhenMessageMovedOutOfSpamMailbox() {
+        MessageMoveEvent messageMoveEvent = MessageMoveEvent.builder()
+            .session(MAILBOX_SESSION)
+            .messageMoves(MessageMoves.builder()
+                .previousMailboxIds(spamMailboxId)
+                .targetMailboxIds(mailboxId2)
+                .build())
+            .messageId(MESSAGE_ID)
+            .build();
+
+        assertThat(listener.isMessageMovedOutOfSpamMailbox(messageMoveEvent)).isTrue();
+    }
+
+    @Test
+    void isMessageMovedOutOfSpamMailboxShouldReturnFalseWhenMessageMovedToTrash() {
+        MessageMoveEvent messageMoveEvent = MessageMoveEvent.builder()
+            .session(MAILBOX_SESSION)
+            .messageMoves(MessageMoves.builder()
+                .previousMailboxIds(spamMailboxId)
+                .targetMailboxIds(trashMailboxId)
+                .build())
+            .messageId(MESSAGE_ID)
+            .build();
+
+        assertThat(listener.isMessageMovedOutOfSpamMailbox(messageMoveEvent)).isFalse();
+    }
+
+    @Test
+    void eventShouldCallSpamAssassinHamLearningWhenTheEventMatches() throws Exception {
+        MessageMoveEvent messageMoveEvent = MessageMoveEvent.builder()
+            .session(MAILBOX_SESSION)
+            .messageMoves(MessageMoves.builder()
+                .previousMailboxIds(spamMailboxId)
+                .targetMailboxIds(mailboxId1)
+                .build())
+            .messageId(MESSAGE_ID)
+            .build();
+
+        listener.event(messageMoveEvent);
+
+        verify(spamAssassinLearner).learnHam(any(), any());
+    }
+
+    @Test
+    void eventShouldCallSpamAssassinHamLearningWhenTheMessageIsAddedInInbox() throws Exception {
+        SimpleMailboxMessage message = createMessage(inbox);
+
+        Added addedEvent = EventFactory.added()
+            .randomEventId()
+            .mailboxSession(MAILBOX_SESSION)
+            .mailbox(inbox)
+            .addMetaData(message.metaData())
+            .build();
+
+        listener.event(addedEvent);
+
+        verify(spamAssassinLearner).learnHam(any(), any());
+    }
+
+    @Test
+    void eventShouldNotCallSpamAssassinHamLearningWhenTheMessageIsAddedInAMailboxOtherThanInbox() throws Exception {
+        SimpleMailboxMessage message = createMessage(mailbox1);
+
+        Added addedEvent = EventFactory.added()
+            .randomEventId()
+            .mailboxSession(MAILBOX_SESSION)
+            .mailbox(mailbox1)
+            .addMetaData(message.metaData())
+            .build();
+
+        listener.event(addedEvent);
+
+        verifyNoMoreInteractions(spamAssassinLearner);
+    }
+
+    private SimpleMailboxMessage createMessage(Mailbox mailbox) throws MailboxException {
+        int size = 45;
+        int bodyStartOctet = 25;
+        byte[] content = "Subject: test\r\n\r\nBody\r\n".getBytes(StandardCharsets.UTF_8);
+        SimpleMailboxMessage message = new SimpleMailboxMessage(MESSAGE_ID, THREAD_ID, new Date(),
+            size, bodyStartOctet, new ByteContent(content), new Flags(), new PropertyBuilder().build(),
+            mailbox.getMailboxId());
+        MessageMetaData messageMetaData = mapperFactory.createMessageMapper(null).add(mailbox, message);
+        message.setUid(messageMetaData.getUid());
+        return message;
+    }
+}
\ No newline at end of file
diff --git a/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinTest.java b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinTest.java
new file mode 100644
index 0000000000..a717108737
--- /dev/null
+++ b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/SpamAssassinTest.java
@@ -0,0 +1,158 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.apache.james.core.MailAddress;
+import org.apache.james.core.builder.MimeMessageBuilder;
+import org.apache.james.domainlist.api.DomainList;
+import org.apache.james.metrics.tests.RecordingMetricFactory;
+import org.apache.james.spamassassin.mock.MockSpamd;
+import org.apache.james.spamassassin.mock.MockSpamdExtension;
+import org.apache.james.user.memory.MemoryUsersRepository;
+import org.apache.james.util.Host;
+import org.apache.mailet.Mail;
+import org.apache.mailet.PerRecipientHeaders;
+import org.apache.mailet.base.test.FakeMail;
+import org.apache.mailet.base.test.FakeMailetConfig;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import com.google.common.collect.ImmutableList;
+
+class SpamAssassinTest {
+
+    private static final DomainList NO_DOMAIN_LIST = null;
+
+    @RegisterExtension
+    MockSpamdExtension spamd = new MockSpamdExtension();
+
+    private SpamAssassin mailet() {
+        return new SpamAssassin(new RecordingMetricFactory(), MemoryUsersRepository.withVirtualHosting(NO_DOMAIN_LIST), new SpamAssassinConfiguration(Host.from("localhost", spamd.getPort())));
+    }
+
+    @Test
+    void serviceShouldWriteSpamAttributeOnMail() throws Exception {
+        FakeMailetConfig mailetConfiguration = FakeMailetConfig.builder()
+            .mailetName("SpamAssassin")
+            .build();
+        SpamAssassin mailet = mailet();
+        mailet.init(mailetConfiguration);
+
+        Mail mail = FakeMail.builder()
+            .name("name")
+            .recipient("user1@exemple.com")
+            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder()
+                .addToRecipient("user1@exemple.com")
+                .addFrom("sender@exemple.com")
+                .setSubject("testing")
+                .setText("Please!")
+                .build())
+            .build();
+
+        mailet.service(mail);
+
+
+        assertThat(
+            mail.getPerRecipientSpecificHeaders()
+                .getHeadersByRecipient()
+                .get(new MailAddress("user1@exemple.com"))
+                .stream()
+                .map(PerRecipientHeaders.Header::getName)
+                .collect(ImmutableList.toImmutableList()))
+            .contains(SpamAssassinResult.FLAG_MAIL.asString(), SpamAssassinResult.STATUS_MAIL.asString());
+    }
+
+    @Test
+    void serviceShouldWriteMessageAsNotSpamWhenNotSpam() throws Exception {
+        FakeMailetConfig mailetConfiguration = FakeMailetConfig.builder()
+            .mailetName("SpamAssassin")
+            .build();
+        SpamAssassin mailet = mailet();
+        mailet.init(mailetConfiguration);
+
+        Mail mail = FakeMail.builder()
+            .name("name")
+            .recipient("user1@exemple.com")
+            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder()
+                .addToRecipient("user1@exemple.com")
+                .addFrom("sender@exemple.com")
+                .setSubject("testing")
+                .setText("Please!")
+                .build())
+            .build();
+
+        mailet.service(mail);
+
+        assertThat(mail.getPerRecipientSpecificHeaders())
+            .isEqualTo(new PerRecipientHeaders()
+                .addHeaderForRecipient(
+                    PerRecipientHeaders.Header.builder()
+                        .name(SpamAssassinResult.FLAG_MAIL.asString())
+                        .value("NO"),
+                    new MailAddress("user1@exemple.com"))
+                .addHeaderForRecipient(
+                    PerRecipientHeaders.Header.builder()
+                        .name(SpamAssassinResult.STATUS_MAIL.asString())
+                        .value("No, hits=3 required=5"),
+                    new MailAddress("user1@exemple.com")));
+    }
+
+    @Test
+    void serviceShouldWriteMessageAsSpamWhenSpam() throws Exception {
+        FakeMailetConfig mailetConfiguration = FakeMailetConfig.builder()
+            .mailetName("SpamAssassin")
+            .build();
+        SpamAssassin mailet = mailet();
+        mailet.init(mailetConfiguration);
+
+        Mail mail = FakeMail.builder()
+            .name("name")
+            .recipient("user1@exemple.com")
+            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder()
+                .addToRecipient("user1@exemple.com")
+                .addFrom("sender@exemple.com")
+                .setSubject(MockSpamd.GTUBE + " testing")
+                .setText("Please!")
+                .build())
+            .build();
+
+        mailet.service(mail);
+
+        assertThat(mail.getPerRecipientSpecificHeaders())
+            .isEqualTo(new PerRecipientHeaders()
+                .addHeaderForRecipient(
+                    PerRecipientHeaders.Header.builder()
+                        .name(SpamAssassinResult.FLAG_MAIL.asString())
+                        .value("YES"),
+                    new MailAddress("user1@exemple.com"))
+                .addHeaderForRecipient(
+                    PerRecipientHeaders.Header.builder()
+                        .name(SpamAssassinResult.STATUS_MAIL.asString())
+                        .value("Yes, hits=1000 required=5"),
+                    new MailAddress("user1@exemple.com")));
+    }
+
+    @Test
+    void getMailetInfoShouldReturnSpamAssasinMailetInformation() {
+        assertThat(mailet().getMailetInfo()).isEqualTo("Checks message against SpamAssassin");
+    }
+}
diff --git a/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/module/SpamAssassinModuleExtension.java b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/module/SpamAssassinModuleExtension.java
new file mode 100644
index 0000000000..d16ad4476f
--- /dev/null
+++ b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/module/SpamAssassinModuleExtension.java
@@ -0,0 +1,65 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin.module;
+
+
+import java.util.Optional;
+
+import org.apache.james.GuiceModuleTestExtension;
+import org.apache.james.spamassassin.SpamAssassinExtension;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.ParameterContext;
+import org.junit.jupiter.api.extension.ParameterResolutionException;
+
+import com.google.inject.Module;
+
+public class SpamAssassinModuleExtension implements GuiceModuleTestExtension {
+
+    private final SpamAssassinExtension spamAssassin;
+
+    public SpamAssassinModuleExtension() {
+        this.spamAssassin = new SpamAssassinExtension();
+    }
+
+    @Override
+    public void beforeAll(ExtensionContext extensionContext) {
+        spamAssassin.beforeAll(extensionContext);
+    }
+
+    @Override
+    public void afterAll(ExtensionContext extensionContext) {
+        spamAssassin.afterAll(extensionContext);
+    }
+
+    @Override
+    public Module getModule() {
+        return new SpamAssassinTestModule(spamAssassin);
+    }
+
+    @Override
+    public Optional<Class<?>> supportedParameterClass() {
+        return Optional.of(SpamAssassinExtension.SpamAssassin.class);
+    }
+
+    @Override
+    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
+        return spamAssassin.getSpamAssassin();
+    }
+}
\ No newline at end of file
diff --git a/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/module/SpamAssassinTestModule.java b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/module/SpamAssassinTestModule.java
new file mode 100644
index 0000000000..c156a46ca1
--- /dev/null
+++ b/third-party/spamassassin/src/test/java/org/apache/james/spamassassin/module/SpamAssassinTestModule.java
@@ -0,0 +1,60 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you 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.                                           *
+ ****************************************************************/
+
+package org.apache.james.spamassassin.module;
+
+import javax.inject.Singleton;
+
+import org.apache.james.mailetcontainer.impl.MailetConfigImpl;
+import org.apache.james.modules.mailbox.ListenerConfiguration;
+import org.apache.james.modules.mailbox.ListenersConfiguration;
+import org.apache.james.spamassassin.SpamAssassin;
+import org.apache.james.spamassassin.SpamAssassinConfiguration;
+import org.apache.james.spamassassin.SpamAssassinExtension;
+import org.apache.james.spamassassin.SpamAssassinListener;
+import org.apache.james.util.Host;
+import org.apache.james.utils.MailetConfigurationOverride;
+
+import com.google.inject.AbstractModule;
+import com.google.inject.Provides;
+import com.google.inject.multibindings.Multibinder;
+
+public class SpamAssassinTestModule extends AbstractModule {
+
+    private final SpamAssassinExtension spamAssassinExtension;
+
+    public SpamAssassinTestModule(SpamAssassinExtension spamAssassinExtension) {
+        this.spamAssassinExtension = spamAssassinExtension;
+    }
+
+    @Override
+    protected void configure() {
+        bind(ListenersConfiguration.class)
+            .toInstance(ListenersConfiguration.of(
+                ListenerConfiguration.forClass(SpamAssassinListener.class.getCanonicalName())));
+    }
+
+    @Provides
+    @Singleton
+    private SpamAssassinConfiguration getSpamAssassinConfiguration() {
+        SpamAssassinExtension.SpamAssassin spamAssassin = spamAssassinExtension.getSpamAssassin();
+        return new SpamAssassinConfiguration(Host.from(spamAssassin.getIp(), spamAssassin.getBindingPort()));
+    }
+
+}
diff --git a/third-party/spamassassin/src/test/resources/docker/spamassassin/spamd.sh b/third-party/spamassassin/src/test/resources/docker/spamassassin/spamd.sh
index 2093cf8f04..31c2261364 100755
--- a/third-party/spamassassin/src/test/resources/docker/spamassassin/spamd.sh
+++ b/third-party/spamassassin/src/test/resources/docker/spamassassin/spamd.sh
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/bin/sh
 
 echo "Run Postgres"
 /usr/local/bin/docker-entrypoint.sh postgres &
diff --git a/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/src/test/resources/listeners.xml b/third-party/spamassassin/src/test/resources/listeners.xml
similarity index 95%
copy from server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/src/test/resources/listeners.xml
copy to third-party/spamassassin/src/test/resources/listeners.xml
index a686755978..cc7c38e00e 100644
--- a/server/protocols/jmap-draft-integration-testing/memory-jmap-draft-integration-testing/src/test/resources/listeners.xml
+++ b/third-party/spamassassin/src/test/resources/listeners.xml
@@ -44,7 +44,7 @@
     </configuration>
   </listener>
   <listener>
-    <class>org.apache.james.mailbox.spamassassin.SpamAssassinListener</class>
+    <class>org.apache.james.spamassassin.SpamAssassinListener</class>
   </listener>
   <listener>
     <class>org.apache.james.jmap.event.PopulateEmailQueryViewListener</class>
diff --git a/third-party/spamassassin/src/test/resources/mailetcontainer.xml b/third-party/spamassassin/src/test/resources/mailetcontainer.xml
new file mode 100644
index 0000000000..f67bfae612
--- /dev/null
+++ b/third-party/spamassassin/src/test/resources/mailetcontainer.xml
@@ -0,0 +1,133 @@
+<?xml version="1.0"?>
+
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you 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.
+ -->
+
+<mailetcontainer enableJmx="false">
+
+    <context>
+        <postmaster>postmaster</postmaster>
+    </context>
+
+    <spooler>
+        <threads>2</threads>
+        <errorRepository>memory://var/mail/error/</errorRepository>
+    </spooler>
+
+    <processors>
+
+        <processor state="root" enableJmx="false">
+            <mailet match="All" class="PostmasterAlias"/>
+            <mailet match="RelayLimit=30" class="Null"/>
+            <mailet match="All" class="ToProcessor">
+                <processor>transport</processor>
+            </mailet>
+        </processor>
+
+        <processor state="error" enableJmx="false">
+            <mailet match="All" class="Bounce">
+                <onMailetException>ignore</onMailetException>
+            </mailet>
+        </processor>
+
+        <processor state="transport" enableJmx="false">
+            <matcher name="mdn-matcher" match="org.apache.james.mailetcontainer.impl.matchers.And">
+                <matcher match="HasMimeType=multipart/report"/>
+                <matcher match="HasMimeTypeParameter=report-type=disposition-notification"/>
+            </matcher>
+            <matcher name="relay-allowed" match="org.apache.james.mailetcontainer.impl.matchers.Or">
+                <matcher match="SMTPAuthSuccessful"/>
+                <matcher match="SMTPIsAuthNetwork"/>
+                <matcher match="SentByMailet"/>
+                <matcher match="org.apache.james.jmap.mailet.SentByJmap"/>
+            </matcher>
+
+            <mailet match="All" class="RemoveMimeHeader">
+                <name>bcc</name>
+            </mailet>
+            <mailet match="All" class="ICSSanitizer"/>
+            <mailet match="All" class="org.apache.james.jmap.mailet.TextCalendarBodyToAttachment"/>
+            <mailet match="All" class="RecipientRewriteTable">
+                <errorProcessor>rrt-error</errorProcessor>
+            </mailet>
+            <mailet match="RecipientIsLocal" class="VacationMailet"/>
+            <mailet match="mdn-matcher" class="org.apache.james.jmap.mailet.ExtractMDNOriginalJMAPMessageId" >
+                <onMailetException>ignore</onMailetException>
+            </mailet>
+            <mailet match="RecipientIsLocal" class="Sieve"/>
+            <mailet match="RecipientIsLocal" class="org.apache.james.spamassassin.SpamAssassin">
+                <onMailetException>ignore</onMailetException>
+            </mailet>
+            <mailet match="IsMarkedAsSpam" class="WithStorageDirective">
+                <targetFolderName>Spam</targetFolderName>
+            </mailet>
+            <mailet match="RecipientIsLocal" class="org.apache.james.jmap.mailet.filter.JMAPFiltering"/>
+            <mailet match="RecipientIsLocal" class="LocalDelivery"/>
+            <mailet match="HostIsLocal" class="ToProcessor">
+                <processor>local-address-error</processor>
+                <notice>550 - Requested action not taken: no such user here</notice>
+            </mailet>
+
+            <mailet match="relay-allowed" class="RemoteDelivery">
+                <outgoingQueue>outgoing</outgoingQueue>
+                <delayTime>5000, 100000, 500000</delayTime>
+                <maxRetries>3</maxRetries>
+                <maxDnsProblemRetries>0</maxDnsProblemRetries>
+                <deliveryThreads>10</deliveryThreads>
+                <sendpartial>true</sendpartial>
+                <bounceProcessor>bounces</bounceProcessor>
+            </mailet>
+
+            <mailet match="All" class="ToProcessor">
+                <processor>relay-denied</processor>
+            </mailet>
+        </processor>
+
+        <processor state="local-address-error" enableJmx="false">
+            <mailet match="All" class="Bounce">
+                <attachment>none</attachment>
+            </mailet>
+        </processor>
+
+        <processor state="relay-denied" enableJmx="false">
+            <mailet match="All" class="Bounce">
+                <attachment>none</attachment>
+            </mailet>
+        </processor>
+
+        <processor state="bounces" enableJmx="false">
+            <mailet match="All" class="DSNBounce">
+                <passThrough>false</passThrough>
+            </mailet>
+        </processor>
+
+        <processor state="rrt-error" enableJmx="false">
+            <mailet match="All" class="ToRepository">
+                <repositoryPath>memory://var/mail/rrt-error/</repositoryPath>
+                <passThrough>true</passThrough>
+            </mailet>
+            <mailet match="IsSenderInRRTLoop" class="Null"/>
+            <mailet match="All" class="Bounce"/>
+        </processor>
+
+    </processors>
+
+</mailetcontainer>
+
+
diff --git a/third-party/spamassassin/src/test/resources/smtpserver.xml b/third-party/spamassassin/src/test/resources/smtpserver.xml
new file mode 100644
index 0000000000..02fbbdadf5
--- /dev/null
+++ b/third-party/spamassassin/src/test/resources/smtpserver.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0"?>
+
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you 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.
+ -->
+
+<smtpservers>
+    <smtpserver enabled="true">
+        <jmxName>smtpserver-global</jmxName>
+        <bind>0.0.0.0:0</bind>
+        <connectionBacklog>200</connectionBacklog>
+        <tls socketTLS="false" startTLS="false">
+            <keystore>file://conf/keystore</keystore>
+            <secret>james72laBalle</secret>
+            <provider>org.bouncycastle.jce.provider.BouncyCastleProvider</provider>
+            <algorithm>SunX509</algorithm>
+        </tls>
+        <connectiontimeout>360</connectiontimeout>
+        <connectionLimit>0</connectionLimit>
+        <connectionLimitPerIP>0</connectionLimitPerIP>
+        <auth>
+            <announce>never</announce>
+            <requireSSL>false</requireSSL>
+            <plainAuthEnabled>true</plainAuthEnabled>
+        </auth>
+        <verifyIdentity>false</verifyIdentity>
+        <maxmessagesize>0</maxmessagesize>
+        <addressBracketsEnforcement>true</addressBracketsEnforcement>
+        <smtpGreeting>Apache JAMES awesome SMTP Server</smtpGreeting>
+        <handlerchain>
+            <handler class="org.apache.james.smtpserver.fastfail.ValidRcptHandler"/>
+            <handler class="org.apache.james.smtpserver.CoreCmdHandlerLoader"/>
+            <handler class="org.apache.james.spamassassin.SpamAssassinHandler"/>
+        </handlerchain>
+        <gracefulShutdown>false</gracefulShutdown>
+    </smtpserver>
+</smtpservers>
+
+


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org