소스 검색

云帆bug修复

24282 2 년 전
부모
커밋
ec33f54aac
50개의 변경된 파일397개의 추가작업 그리고 6828개의 파일을 삭제
  1. 4 54
      bladex-saas-project/new-mail/pom.xml
  2. 11 2
      bladex-saas-project/new-mail/src/main/java/com/fjhx/back/test/IMAPReceiveMailTest.java
  3. 91 100
      bladex-saas-project/new-mail/src/main/java/com/fjhx/back/test/NewTest.java
  4. 20 0
      bladex-saas-project/new-mail/src/main/java/com/fjhx/config/TransactionConfig.java
  5. 1 1
      bladex-saas-project/new-mail/src/main/java/com/fjhx/entity/MailAddress.java
  6. 12 0
      bladex-saas-project/new-mail/src/main/java/com/fjhx/entity/MailFolder.java
  7. 5 0
      bladex-saas-project/new-mail/src/main/java/com/fjhx/entity/MailInfo.java
  8. 0 10
      bladex-saas-project/new-mail/src/main/java/com/fjhx/entity/Mailbox.java
  9. 1 1
      bladex-saas-project/new-mail/src/main/java/com/fjhx/enums/MailFlagEnum.java
  10. 0 4
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/CoreService.java
  11. 0 5
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailAddressService.java
  12. 0 5
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailAttachmentService.java
  13. 0 1
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailFolderService.java
  14. 0 5
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailInfoService.java
  15. 0 5
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailMessageService.java
  16. 0 1
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailboxService.java
  17. 134 149
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/CoreServiceImpl.java
  18. 0 47
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/MailAddressServiceImpl.java
  19. 35 43
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/MailAttachmentServiceImpl.java
  20. 0 92
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/MailInfoServiceImpl.java
  21. 0 21
      bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/MailMessageServiceImpl.java
  22. 79 0
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/EmailUtil.java
  23. 0 809
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/CommonEmail.java
  24. 0 129
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EMLComposer.java
  25. 0 126
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EMLParser.java
  26. 0 131
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EMLProperties.java
  27. 0 185
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/Email.java
  28. 0 233
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailAddress.java
  29. 0 296
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailAttachment.java
  30. 0 288
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailAttachmentBuilder.java
  31. 0 395
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailFilter.java
  32. 0 99
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailMessage.java
  33. 0 222
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailUtil.java
  34. 0 99
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ImapServer.java
  35. 0 90
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ImapSslServer.java
  36. 0 62
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/MailException.java
  37. 0 373
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/MailServer.java
  38. 0 123
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/MailSession.java
  39. 0 104
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/Pop3Server.java
  40. 0 87
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/Pop3SslServer.java
  41. 0 730
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/RFC2822AddressParser.java
  42. 0 413
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ReceiveMailSession.java
  43. 0 515
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ReceivedEmail.java
  44. 0 133
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ReceiverBuilder.java
  45. 0 361
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/SendMailSession.java
  46. 0 60
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/SimpleAuthenticator.java
  47. 0 111
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/SmtpServer.java
  48. 0 105
      bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/SmtpSslServer.java
  49. 2 2
      bladex-saas-project/saas-mail-grad-online/src/main/java/com/fjhx/mail/grad/service/impl/GrabMailLogicServiceImpl.java
  50. 2 1
      bladex-saas-project/saas-mail-grad-online/src/main/java/com/fjhx/mail/grad/service/impl/GrabMailServiceImpl.java

+ 4 - 54
bladex-saas-project/new-mail/pom.xml

@@ -37,63 +37,13 @@
 
         <dependency>
             <groupId>org.springblade</groupId>
-            <artifactId>blade-core-cloud</artifactId>
-        </dependency>
-
-<!--        <dependency>-->
-<!--            <groupId>com.sun.mail</groupId>-->
-<!--            <artifactId>jakarta.mail</artifactId>-->
-<!--        </dependency>-->
-
-        <!--        <dependency>-->
-        <!--            <groupId>org.apache.commons</groupId>-->
-        <!--            <artifactId>commons-email</artifactId>-->
-        <!--            <version>1.5</version>-->
-        <!--        </dependency>-->
-
-
-        <!--        <dependency>-->
-        <!--            <groupId>org.springframework.boot</groupId>-->
-        <!--            <artifactId>spring-boot-starter-mail</artifactId>-->
-        <!--            <version>3.0.4</version>-->
-        <!--        </dependency>-->
-
-
-
-        <dependency>
-            <groupId>jakarta.activation</groupId>
-            <artifactId>jakarta.activation-api</artifactId>
-            <version>2.1.1</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.eclipse.angus</groupId>
-            <artifactId>jakarta.mail</artifactId>
-            <version>1.0.0</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.jodd</groupId>
-            <artifactId>jodd-util</artifactId>
-            <version>6.0.1</version>
-        </dependency>
-
-        <dependency>
-            <groupId>com.sun.mail</groupId>
-            <artifactId>jakarta.mail</artifactId>
-            <version>1.6.7</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.eclipse.angus</groupId>
-            <artifactId>jakarta.mail</artifactId>
-            <version>2.0.1</version>
+            <artifactId>blade-resource-api</artifactId>
+            <version>2.8.2.RELEASE</version>
         </dependency>
 
         <dependency>
-            <groupId>org.springblade</groupId>
-            <artifactId>blade-resource-api</artifactId>
-            <version>2.8.2.RELEASE</version>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-mail</artifactId>
         </dependency>
 
     </dependencies>

+ 11 - 2
bladex-saas-project/new-mail/src/main/java/com/fjhx/back/test/IMAPReceiveMailTest.java

@@ -5,7 +5,9 @@ import cn.hutool.extra.mail.Mail;
 import com.alibaba.fastjson.JSONObject;
 import com.fjhx.entity.Mailbox;
 import com.maxmind.geoip2.DatabaseReader;
+import com.sun.mail.imap.IMAPFolder;
 import com.sun.mail.imap.IMAPMessage;
+import com.sun.mail.imap.IMAPStore;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.collections4.CollectionUtils;
 import org.apache.commons.collections4.MapUtils;
@@ -47,14 +49,21 @@ public class IMAPReceiveMailTest {
 
         // 创建IMAP协议的Store对象
         // Store store = session.getStore("imap");
-        Store store = session.getStore("imap");
+        IMAPStore store = (IMAPStore)session.getStore("imap");
+
+        Folder defaultFolder = store.getDefaultFolder();
+        Folder[] list = defaultFolder.list();
+
+
 
         // 连接邮件服务器
         // store.connect("sale3@bridge-style.cc", "peQ8ztVZ6f8F2sp5");
         store.connect("imap.qq.com", 993, "2428241269@qq.com", "kdypajdrwfhtdihb");
 
         // 获得收件箱
-        Folder folder = store.getFolder("INBOX");
+        IMAPFolder folder = (IMAPFolder)store.getFolder("INBOX");
+
+
         // 以读写模式打开收件箱
         folder.open(Folder.READ_WRITE);
 

+ 91 - 100
bladex-saas-project/new-mail/src/main/java/com/fjhx/back/test/NewTest.java

@@ -6,17 +6,8 @@ package com.fjhx.back.test;
 // import jakarta.mail.internet.MimeUtility;
 // import jakarta.mail.search.FlagTerm;
 
-import com.fjhx.utils.mail.*;
-import jakarta.activation.DataSource;
-import jakarta.mail.Flags;
 import lombok.SneakyThrows;
 
-import javax.mail.internet.MimeUtility;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.util.Date;
-import java.util.List;
-
 public class NewTest {
 
 
@@ -29,13 +20,13 @@ public class NewTest {
         //         .ssl(true)
         //         .buildImapMailServer();
 
-        ImapServer imapServer = MailServer.create()
-                .auth("sale12@bridge-style.cc", "59amYpMFaZL7EWK4")
-                .host("imap.qiye.163.com")
-                .port(993)
-                .ssl(true)
-                .strictAddress(true)
-                .buildImapMailServer();
+        // ImapServer imapServer = MailServer.create()
+        //         .auth("sale12@bridge-style.cc", "59amYpMFaZL7EWK4")
+        //         .host("imap.qiye.163.com")
+        //         .port(993)
+        //         .ssl(true)
+        //         .strictAddress(true)
+        //         .buildImapMailServer();
 
 
         // boolean isSSL = true;
@@ -109,90 +100,90 @@ public class NewTest {
         //         .buildImapMailServer();
         //
         //
-        ReceiveMailSession session = imapServer.createSession();
-
-        session.open();
-
-        String[] allFolders = session.getAllFolders();
-
-        // 收到的邮件数量
-        System.out.println(session.getMessageCount());
-
-
-        ReceivedEmail[] receivedEmails = session.receiveEmailAndMarkSeen();
-        for (ReceivedEmail receivedEmail : receivedEmails) {
-
-            String fullName = receivedEmail.originalMessage().getFolder().getFullName();
-            EmailAddress[] cc = receivedEmail.cc();
-            EmailAddress[] to = receivedEmail.to();
-            EmailAddress[] emailAddresses = receivedEmail.replyTo();
-
-            for (EmailAddress emailAddress : emailAddresses) {
-                String personalName = emailAddress.getPersonalName();
-            }
-
-            int i = receivedEmail.messageNumber();
-
-            Flags flags = receivedEmail.flags();
-            String s1 = flags.toString();
-            String[] userFlags = flags.getUserFlags();
-            Flags.Flag[] systemFlags = flags.getSystemFlags();
-            for (Flags.Flag systemFlag : systemFlags) {
-                System.out.println("systemFlag.toString() = " + systemFlag.toString());
-                boolean equals = systemFlag.equals(Flags.Flag.SEEN);
-                System.out.println(equals);
-            }
-
-            EmailAddress from1 = receivedEmail.from();
-
-            String subject = receivedEmail.subject();
-
-            EmailAddress from = receivedEmail.from();
-            String email = from.getEmail();
-            String personalName = from.getPersonalName();
-            String personal = MimeUtility.decodeText(personalName);
-
-            Date date = receivedEmail.receivedDate();
-
-            String messageId = receivedEmail.messageId();
-
-            List<EmailMessage> messages1 = receivedEmail.messages();
-
-            List<EmailAttachment<? extends DataSource>> attachments = receivedEmail.attachments();
-            for (EmailAttachment<? extends DataSource> attachment : attachments) {
-                String name = attachment.getName();
-                int size = attachment.getSize();
-                String contentId = attachment.getContentId();
-                String encodedName = attachment.getEncodedName();
-
-                String s = MimeUtility.decodeText(encodedName);
-
-                byte[] bytes = attachment.toByteArray();
-
-                FileOutputStream outputStream = new FileOutputStream("D:\\24282\\Desktop\\任务\\测试1.xls");
-                outputStream.write(bytes);
-
-
-                attachment.writeToFile(new File("D:\\24282\\Desktop\\任务\\测试2.xls"));
-
-                System.out.println();
-            }
-
-
-            List<ReceivedEmail> receivedEmails2 = receivedEmail.attachedMessages();
-
-            for (ReceivedEmail receivedEmail1 : receivedEmails2) {
-                return;
-            }
-
-
-            List<EmailMessage> messages = receivedEmail.messages();
-
-            for (EmailMessage message : messages) {
-                message.getMimeType();
-            }
-        }
-        session.close();
+        // ReceiveMailSession session = imapServer.createSession();
+        //
+        // session.open();
+        //
+        // String[] allFolders = session.getAllFolders();
+        //
+        // // 收到的邮件数量
+        // System.out.println(session.getMessageCount());
+        //
+        //
+        // ReceivedEmail[] receivedEmails = session.receiveEmail();
+        // for (ReceivedEmail receivedEmail : receivedEmails) {
+        //
+        //     String fullName = receivedEmail.originalMessage().getFolder().getFullName();
+        //     EmailAddress[] cc = receivedEmail.cc();
+        //     EmailAddress[] to = receivedEmail.to();
+        //     EmailAddress[] emailAddresses = receivedEmail.replyTo();
+        //
+        //     for (EmailAddress emailAddress : emailAddresses) {
+        //         String personalName = emailAddress.getPersonalName();
+        //     }
+        //
+        //     int i = receivedEmail.messageNumber();
+        //
+        //     Flags flags = receivedEmail.flags();
+        //     String s1 = flags.toString();
+        //     String[] userFlags = flags.getUserFlags();
+        //     Flags.Flag[] systemFlags = flags.getSystemFlags();
+        //     for (Flags.Flag systemFlag : systemFlags) {
+        //         System.out.println("systemFlag.toString() = " + systemFlag.toString());
+        //         boolean equals = systemFlag.equals(Flags.Flag.SEEN);
+        //         System.out.println(equals);
+        //     }
+        //
+        //     EmailAddress from1 = receivedEmail.from();
+        //
+        //     String subject = receivedEmail.subject();
+        //
+        //     EmailAddress from = receivedEmail.from();
+        //     String email = from.getEmail();
+        //     String personalName = from.getPersonalName();
+        //     String personal = MimeUtility.decodeText(personalName);
+        //
+        //     Date date = receivedEmail.receivedDate();
+        //
+        //     String messageId = receivedEmail.messageId();
+        //
+        //     List<EmailMessage> messages1 = receivedEmail.messages();
+        //
+        //     List<EmailAttachment<? extends DataSource>> attachments = receivedEmail.attachments();
+        //     for (EmailAttachment<? extends DataSource> attachment : attachments) {
+        //         String name = attachment.getName();
+        //         int size = attachment.getSize();
+        //         String contentId = attachment.getContentId();
+        //         String encodedName = attachment.getEncodedName();
+        //
+        //         String s = MimeUtility.decodeText(encodedName);
+        //
+        //         byte[] bytes = attachment.toByteArray();
+        //
+        //         FileOutputStream outputStream = new FileOutputStream("D:\\24282\\Desktop\\任务\\测试1.xls");
+        //         outputStream.write(bytes);
+        //
+        //
+        //         attachment.writeToFile(new File("D:\\24282\\Desktop\\任务\\测试2.xls"));
+        //
+        //         System.out.println();
+        //     }
+        //
+        //
+        //     List<ReceivedEmail> receivedEmails2 = receivedEmail.attachedMessages();
+        //
+        //     for (ReceivedEmail receivedEmail1 : receivedEmails2) {
+        //         return;
+        //     }
+        //
+        //
+        //     List<EmailMessage> messages = receivedEmail.messages();
+        //
+        //     for (EmailMessage message : messages) {
+        //         message.getMimeType();
+        //     }
+        // }
+        // session.close();
 
         // ImapServer imapServer = MailServer.create()
         //         .auth("sale12@bridge-style.cc", "59amYpMFaZL7EWK4")

+ 20 - 0
bladex-saas-project/new-mail/src/main/java/com/fjhx/config/TransactionConfig.java

@@ -0,0 +1,20 @@
+package com.fjhx.config;
+
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class TransactionConfig {
+
+    // @Autowired
+    // private PlatformTransactionManager platformTransactionManager;
+    //
+    //
+    //
+    // @Bean
+    // @ConditionalOnMissingBean
+    // public TransactionTemplate transactionTemplate() {
+    //     return new TransactionTemplate(this.platformTransactionManager);
+    // }
+
+
+}

+ 1 - 1
bladex-saas-project/new-mail/src/main/java/com/fjhx/entity/MailAddress.java

@@ -35,7 +35,7 @@ public class MailAddress implements Serializable {
     private Long mailInfoId;
 
     /**
-     * 类型 1收件人(to) 2抄送人(cc) 3回复人(replyTo)
+     * 类型 1收件人(to) 2抄送人(cc) 3密送人(bcc) 4回复人(replyTo)
      */
     private Integer type;
 

+ 12 - 0
bladex-saas-project/new-mail/src/main/java/com/fjhx/entity/MailFolder.java

@@ -7,6 +7,7 @@ import lombok.Getter;
 import lombok.Setter;
 
 import java.io.Serializable;
+import java.util.Date;
 
 /**
  * <p>
@@ -38,4 +39,15 @@ public class MailFolder implements Serializable {
      * 文件夹名称
      */
     private String name;
+
+    /**
+     * 上次邮件id
+     */
+    private String lastMessageId;
+
+    /**
+     * 上次同步时间
+     */
+    private Date lastReceivedDate;
+
 }

+ 5 - 0
bladex-saas-project/new-mail/src/main/java/com/fjhx/entity/MailInfo.java

@@ -76,6 +76,11 @@ public class MailInfo implements Serializable {
     private String fromPersonalName;
 
     /**
+     * 发件类型
+     */
+    private String fromType;
+
+    /**
      * 发件时间
      */
     private Date sendDate;

+ 0 - 10
bladex-saas-project/new-mail/src/main/java/com/fjhx/entity/Mailbox.java

@@ -75,14 +75,4 @@ public class Mailbox implements Serializable {
      */
     private Integer smtpPort;
 
-    /**
-     * 上次邮件id
-     */
-    private String lastMessageId;
-
-    /**
-     * 上次同步时间
-     */
-    private Date lastReceivedDate;
-
 }

+ 1 - 1
bladex-saas-project/new-mail/src/main/java/com/fjhx/enums/MailFlagEnum.java

@@ -1,9 +1,9 @@
 package com.fjhx.enums;
 
-import jakarta.mail.Flags;
 import lombok.AllArgsConstructor;
 import lombok.Getter;
 
+import javax.mail.Flags;
 import java.util.HashMap;
 import java.util.Map;
 

+ 0 - 4
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/CoreService.java

@@ -1,4 +0,0 @@
-package com.fjhx.service;
-
-public interface CoreService {
-}

+ 0 - 5
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailAddressService.java

@@ -2,9 +2,6 @@ package com.fjhx.service;
 
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.fjhx.entity.MailAddress;
-import com.fjhx.utils.mail.ReceivedEmail;
-
-import java.util.List;
 
 /**
  * <p>
@@ -16,6 +13,4 @@ import java.util.List;
  */
 public interface MailAddressService extends IService<MailAddress> {
 
-    List<MailAddress> getMailAddress(Long mailInfoId, ReceivedEmail receivedEmail);
-
 }

+ 0 - 5
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailAttachmentService.java

@@ -2,9 +2,6 @@ package com.fjhx.service;
 
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.fjhx.entity.MailAttachment;
-import com.fjhx.utils.mail.ReceivedEmail;
-
-import java.util.List;
 
 /**
  * <p>
@@ -16,6 +13,4 @@ import java.util.List;
  */
 public interface MailAttachmentService extends IService<MailAttachment> {
 
-    List<MailAttachment> getMailAttachment(Long mailInfoId, ReceivedEmail receivedEmail);
-
 }

+ 0 - 1
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailFolderService.java

@@ -2,7 +2,6 @@ package com.fjhx.service;
 
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.fjhx.entity.MailFolder;
-import org.springblade.core.mp.base.BaseService;
 
 /**
  * <p>

+ 0 - 5
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailInfoService.java

@@ -2,9 +2,6 @@ package com.fjhx.service;
 
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.fjhx.entity.MailInfo;
-import com.fjhx.utils.mail.ReceivedEmail;
-
-import java.util.Map;
 
 /**
  * <p>
@@ -16,6 +13,4 @@ import java.util.Map;
  */
 public interface MailInfoService extends IService<MailInfo> {
 
-    MailInfo getMailInfo(String mailboxId, Map<String, Long> folderMap, ReceivedEmail receivedEmail);
-
 }

+ 0 - 5
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailMessageService.java

@@ -2,9 +2,6 @@ package com.fjhx.service;
 
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.fjhx.entity.MailMessage;
-import com.fjhx.utils.mail.ReceivedEmail;
-
-import java.util.List;
 
 /**
  * <p>
@@ -16,6 +13,4 @@ import java.util.List;
  */
 public interface MailMessageService extends IService<MailMessage> {
 
-    List<MailMessage> getMailMessage(Long mailInfoId, ReceivedEmail receivedEmail);
-
 }

+ 0 - 1
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/MailboxService.java

@@ -2,7 +2,6 @@ package com.fjhx.service;
 
 import com.baomidou.mybatisplus.extension.service.IService;
 import com.fjhx.entity.Mailbox;
-import org.springblade.core.mp.base.BaseService;
 
 /**
  * <p>

+ 134 - 149
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/CoreServiceImpl.java

@@ -5,13 +5,15 @@ import cn.hutool.core.util.ObjectUtil;
 import com.alibaba.fastjson.JSON;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.fjhx.config.TaskPoolConfig;
-import com.fjhx.entity.*;
-import com.fjhx.service.*;
-import com.fjhx.utils.mail.ImapServer;
-import com.fjhx.utils.mail.MailServer;
-import com.fjhx.utils.mail.ReceiveMailSession;
-import com.fjhx.utils.mail.ReceivedEmail;
-import lombok.AllArgsConstructor;
+import com.fjhx.entity.MailFolder;
+import com.fjhx.entity.MailInfo;
+import com.fjhx.entity.Mailbox;
+import com.fjhx.service.MailFolderService;
+import com.fjhx.service.MailInfoService;
+import com.fjhx.service.MailboxService;
+import com.fjhx.utils.EmailUtil;
+import com.sun.mail.imap.IMAPMessage;
+import com.sun.mail.imap.IMAPStore;
 import lombok.extern.slf4j.Slf4j;
 import org.springblade.core.tool.utils.ThreadUtil;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -22,34 +24,42 @@ import org.springframework.transaction.TransactionDefinition;
 import org.springframework.transaction.TransactionStatus;
 
 import javax.annotation.PostConstruct;
-import java.util.*;
+import javax.mail.Folder;
+import javax.mail.FolderNotFoundException;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.internet.InternetAddress;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
-import java.util.stream.Collectors;
 
 @Slf4j
 @Service
-@AllArgsConstructor
-public class CoreServiceImpl implements CoreService {
+// @AllArgsConstructor
+public class CoreServiceImpl {
 
-    private final MailboxService mailboxService;
-    private final MailFolderService mailFolderService;
-    private final MailInfoService mailInfoService;
-    private final MailAddressService mailAddressService;
-    private final MailMessageService mailMessageService;
-    private final MailAttachmentService mailAttachmentService;
-
-
-    private final PlatformTransactionManager platformTransactionManager;
-    private final TransactionDefinition transactionDefinition;
+    @Autowired
+    private MailboxService mailboxService;
+    @Autowired
+    private MailFolderService mailFolderService;
+    @Autowired
+    private MailInfoService mailInfoService;
+    // private final MailAddressService mailAddressService;
+    // private final MailMessageService mailMessageService;
+    // private final MailAttachmentService mailAttachmentService;
 
+    @Autowired
+    @Qualifier(TaskPoolConfig.emailTaskExecutor)
     private Executor emailTaskExecutor;
 
     @Autowired
-    @Qualifier(TaskPoolConfig.emailTaskExecutor)
-    public void setEmailTaskExecutor(Executor emailTaskExecutor) {
-        this.emailTaskExecutor = emailTaskExecutor;
-    }
+    private PlatformTransactionManager platformTransactionManager;
+
+    @Autowired
+    private TransactionDefinition transactionDefinition;
+
 
     // 累计同步次数
     private static int num = 0;
@@ -84,8 +94,11 @@ public class CoreServiceImpl implements CoreService {
         for (Mailbox mailbox : list) {
             // 开启异步操作
             emailTaskExecutor.execute(() -> {
-                saveMailList(mailbox);
-                countDownLatch.countDown();
+                try {
+                    synchronousMail(mailbox);
+                } finally {
+                    countDownLatch.countDown();
+                }
             });
         }
 
@@ -114,160 +127,132 @@ public class CoreServiceImpl implements CoreService {
 
     }
 
-    private static final Properties props = new Properties();
-
-    static {
-        props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
-    }
-
-
     /**
-     * 保存邮件信息
+     * 同步邮箱
      */
-    private void saveMailList(Mailbox mailbox) {
-
-        ReceiveMailSession session = null;
-        try {
-            ImapServer imapServer = MailServer.create()
-                    .auth(mailbox.getMailboxName(), mailbox.getMailboxPwd())
-                    .host(mailbox.getMailHost())
-                    .port(993)
-                    .ssl(true)
-                    .buildImapMailServer();
-
-            session = imapServer.createSession();
-            session.open();
+    private void synchronousMail(Mailbox mailbox) {
 
-            synchronousMessage(mailbox, session);
+        // 获取所有文件夹
+        List<MailFolder> mailFolderList = mailFolderService.list(Wrappers.<MailFolder>lambdaQuery().eq(MailFolder::getMailboxId, mailbox));
 
-        } catch (Exception e) {
-            log.error("链接imap出错,邮箱信息:{}", JSON.toJSONString(mailbox));
-        } finally {
-            if (session != null) {
-                session.close();
-            }
-        }
-    }
+        IMAPStore store = null;
 
-    /**
-     * 同步邮件方法
-     * 这里不做业务处理,只做异常捕获和非异常事务提交
-     */
-    private void synchronousMessage(Mailbox mailbox, ReceiveMailSession session) {
-        TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
         try {
-            doSynchronousMessage(mailbox, session);
-            // 事务提交
-            platformTransactionManager.commit(transactionStatus);
-        } catch (Exception e) {
-            log.error("同步邮箱发生错误", e);
-            // 事务回滚
-            platformTransactionManager.rollback(transactionStatus);
-        }
-    }
-
-    /**
-     * 真正开始开始同步邮件业务操作
-     */
-    private void doSynchronousMessage(Mailbox mailbox, ReceiveMailSession session) throws Exception {
+            store = EmailUtil.getIMAPStore(mailbox.getMailHost(), mailbox.getMailboxName(), mailbox.getMailboxPwd());
 
-        String lastMessageId = mailbox.getLastMessageId();
-        Date lastReceivedDate = mailbox.getLastReceivedDate();
-
-        // 如果没有上次同步id和上次同步时间,执行初始化逻辑
-        if (ObjectUtil.isAllNotEmpty(lastMessageId, lastReceivedDate)) {
-
-            String[] folders = session.getAllFolders();
-
-            // 保存文件夹
-            List<MailFolder> mailFolderList = Arrays.stream(folders).map(folder -> {
-                MailFolder mailFolder = new MailFolder();
-                mailFolder.setName(folder);
-                mailFolder.setMailboxId(mailbox.getId());
-                return mailFolder;
-            }).collect(Collectors.toList());
-
-            // 文件夹map
-            Map<String, Long> folderMap = mailFolderList.stream().collect(Collectors.toMap(MailFolder::getName, MailFolder::getId));
-
-            // 获取同步邮件时间
-            Date minimumTime = DateUtil.offsetDay(new Date(), -initDay);
-
-            ReceivedEmail[] receivedEmails = session.receiveEmail();
+            // 文件夹为空,代表初始化,从官方邮箱重新拉取文件夹
+            if (mailFolderList.size() == 0) {
+                mailFolderList = EmailUtil.createMailFolderList(store, mailbox.getId());
+                mailFolderService.saveBatch(mailFolderList);
+            }
 
-            ReceivedEmail receivedEmail = receivedEmails[0];
-            mailbox.setLastMessageId(receivedEmail.messageId());
-            mailbox.setLastReceivedDate(receivedEmail.receivedDate());
-            mailboxService.updateById(mailbox);
+            // 分别拉取每个文件夹邮件
+            for (MailFolder mailFolder : mailFolderList) {
+                Folder folder = store.getFolder(mailFolder.getName());
 
-            // 遍历邮件
-            for (ReceivedEmail receivedEmail1 : receivedEmails) {
-                Date date = receivedEmail1.receivedDate();
-                if (date.after(minimumTime)) {
-                    saveMail(mailbox.getId(), folderMap, receivedEmail1);
+                try {
+                    // 只读方式打开收件箱
+                    folder.open(Folder.READ_ONLY);
+                } catch (FolderNotFoundException folderNotFoundException) {
+                    // 邮箱不存在,则删除文件夹记录
+                    mailFolderService.removeById(mailFolder.getId());
                     continue;
                 }
-                break;
-            }
+                try {
+                    Message[] messages = folder.getMessages();
+                    List<MailInfo> mailInfoList = getMailInfoList(mailFolder, messages);
 
 
-        } else {
+                    IMAPMessage message = (IMAPMessage) messages[0];
+                    mailFolder.setLastMessageId(message.getMessageID());
+                    mailFolder.setLastReceivedDate(message.getReceivedDate());
 
-            // 获取所有邮件
-            ReceivedEmail[] receivedEmails = session.receiveEmail();
+                    saveMailInfo(mailFolder, mailInfoList);
 
-            ReceivedEmail lastReceivedEmail = receivedEmails[0];
-            mailbox.setLastMessageId(lastReceivedEmail.messageId());
-            mailbox.setLastReceivedDate(lastReceivedEmail.receivedDate());
-            mailboxService.updateById(mailbox);
+                } finally {
+                    folder.close();
+                }
+            }
 
-            for (ReceivedEmail receivedEmail : receivedEmails) {
-                String mailboxId = mailbox.getId();
+        } catch (Exception e) {
+            log.error("链接imap出错,邮箱信息:{}", JSON.toJSONString(mailbox));
+        } finally {
+            if (store != null) {
+                try {
+                    store.close();
+                } catch (MessagingException e) {
+                    log.error("store关闭失败", e);
+                }
+            }
+        }
+    }
 
-                List<MailFolder> list = mailFolderService.list(Wrappers.<MailFolder>lambdaQuery().eq(MailFolder::getMailboxId, mailboxId));
-                Map<String, Long> mailFolderMap = list.stream().collect(Collectors.toMap(MailFolder::getName, MailFolder::getId));
+    private List<MailInfo> getMailInfoList(MailFolder mailFolder, Message[] messages) throws MessagingException {
+        String lastMessageId = mailFolder.getLastMessageId();
+        Date lastReceivedDate = ObjectUtil.defaultIfNull(mailFolder.getLastReceivedDate(),
+                DateUtil.offsetDay(new Date(), -initDay));
 
-                Date date = receivedEmail.receivedDate();
-                String messageId = receivedEmail.messageId();
+        List<MailInfo> mailInfoList = new ArrayList<>();
 
-                if (Objects.equals(messageId, lastMessageId)) {
-                    break;
-                }
+        int length = messages.length;
+        for (int i = length - 1; i >= 0; i--) {
+            IMAPMessage message = (IMAPMessage) messages[i];
+            // 邮件发送时间
+            Date receivedDate = message.getReceivedDate();
+            // 邮件id
+            String messageID = message.getMessageID();
 
-                if (date.after(lastReceivedDate)) {
-                    saveMail(mailboxId, mailFolderMap, receivedEmail);
-                } else {
+            if (ObjectUtil.isNotEmpty(lastMessageId)) {
+                if (lastMessageId.equals(messageID)) {
                     break;
                 }
-
+            }
+            if (lastReceivedDate.before(receivedDate)) {
+                break;
             }
 
+            MailInfo mailInfo = new MailInfo();
+            mailInfo.setMailboxId(mailFolder.getMailboxId());
+            mailInfo.setMessageId(messageID);
+            mailInfo.setMessageNumber(message.getMessageNumber());
+            mailInfo.setSubject(message.getSubject());
+            mailInfo.setFlags(EmailUtil.getFlags(message.getFlags()));
+            mailInfo.setFolderId(mailFolder.getId());
+            mailInfo.setFolderName(mailFolder.getName());
+
+            InternetAddress internetAddress = (InternetAddress) message.getSender();
+            mailInfo.setFromEmail(internetAddress.getAddress());
+            mailInfo.setFromPersonalName(internetAddress.getPersonal());
+            mailInfo.setFromType(internetAddress.getType());
+            mailInfo.setSendDate(receivedDate);
+            mailInfo.setCreateTime(new Date());
+            mailInfoList.add(0, mailInfo);
+
+            addMailCount();
         }
 
+        return mailInfoList;
     }
 
-    // 保存邮件
-    // TODO 先简单save,后续优化
-    private void saveMail(String mailboxId, Map<String, Long> folderMap, ReceivedEmail receivedEmail) {
-        MailInfo mailInfo = mailInfoService.getMailInfo(mailboxId, folderMap, receivedEmail);
-        mailInfoService.save(mailInfo);
-
-        Long mailInfoId = mailInfo.getId();
-
-        List<MailAddress> mailAddressList = mailAddressService.getMailAddress(mailInfoId, receivedEmail);
-        mailAddressService.saveBatch(mailAddressList);
-
-        List<MailAttachment> mailAttachmentList = mailAttachmentService.getMailAttachment(mailInfoId, receivedEmail);
-        mailAttachmentService.saveBatch(mailAttachmentList);
-
-        List<MailMessage> mailMessageList = mailMessageService.getMailMessage(mailInfoId, receivedEmail);
-        mailMessageService.saveBatch(mailMessageList);
+    /**
+     * 保存邮件数据
+     */
+    private void saveMailInfo(MailFolder mailFolder, List<MailInfo> mailInfoList) {
+        TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
+        try {
 
-        addMailCount();
+            mailFolderService.updateById(mailFolder);
+            mailInfoService.saveBatch(mailInfoList);
 
+            // 事务提交
+            platformTransactionManager.commit(transactionStatus);
+        } catch (Exception e) {
+            log.error("同步邮箱发生错误", e);
+            // 事务回滚
+            platformTransactionManager.rollback(transactionStatus);
+        }
     }
 
-
     // 添加同步邮件数量
     private static synchronized void addMailCount() {
         mailCount++;

+ 0 - 47
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/MailAddressServiceImpl.java

@@ -1,19 +1,11 @@
 package com.fjhx.service.impl;
 
-import cn.hutool.core.util.ObjectUtil;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.fjhx.entity.MailAddress;
 import com.fjhx.mapper.MailAddressMapper;
 import com.fjhx.service.MailAddressService;
-import com.fjhx.utils.mail.EmailAddress;
-import com.fjhx.utils.mail.ReceivedEmail;
 import org.springframework.stereotype.Service;
 
-import javax.mail.internet.MimeUtility;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-
 /**
  * <p>
  * 邮件关联地址表 服务实现类
@@ -25,44 +17,5 @@ import java.util.List;
 @Service
 public class MailAddressServiceImpl extends ServiceImpl<MailAddressMapper, MailAddress> implements MailAddressService {
 
-    @Override
-    public List<MailAddress> getMailAddress(Long mailInfoId, ReceivedEmail receivedEmail) {
-
-        EmailAddress[] to = receivedEmail.to();
-        List<MailAddress> mailAddressList = new ArrayList<>(getMailAddress(to, mailInfoId, 1));
-
-        EmailAddress[] cc = receivedEmail.cc();
-        mailAddressList.addAll(getMailAddress(cc, mailInfoId, 2));
-
-        EmailAddress[] replyTo = receivedEmail.replyTo();
-        mailAddressList.addAll(getMailAddress(replyTo, mailInfoId, 3));
-
-        return mailAddressList;
-    }
-
-    private List<MailAddress> getMailAddress(EmailAddress[] emailAddresses, Long mailInfoId, Integer type) {
-
-        List<MailAddress> mailAddressList = new ArrayList<>();
-
-        for (EmailAddress item : emailAddresses) {
-            MailAddress mailAddress = new MailAddress();
-            mailAddress.setMailInfoId(mailInfoId);
-            mailAddress.setType(1);
-            mailAddress.setEmail(item.getEmail());
-
-            String personalName = item.getPersonalName();
-            if (ObjectUtil.isNotEmpty(personalName)) {
-                try {
-                    mailAddress.setPersonalName(MimeUtility.decodeText(personalName));
-                } catch (UnsupportedEncodingException e) {
-                    throw new RuntimeException(e);
-                }
-            }
-
-            mailAddressList.add(mailAddress);
-        }
-
-        return mailAddressList;
-    }
 
 }

+ 35 - 43
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/MailAttachmentServiceImpl.java

@@ -1,21 +1,13 @@
 package com.fjhx.service.impl;
 
-import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.fjhx.entity.MailAttachment;
 import com.fjhx.mapper.MailAttachmentMapper;
 import com.fjhx.service.MailAttachmentService;
-import com.fjhx.utils.mail.EmailAttachment;
-import com.fjhx.utils.mail.ReceivedEmail;
 import lombok.AllArgsConstructor;
-import org.springblade.core.tool.api.R;
-import org.springblade.resource.entity.ObsUpload;
 import org.springblade.resource.feign.IObsClient;
 import org.springframework.stereotype.Service;
 
-import java.util.ArrayList;
-import java.util.List;
-
 /**
  * <p>
  * 服务实现类
@@ -30,39 +22,39 @@ public class MailAttachmentServiceImpl extends ServiceImpl<MailAttachmentMapper,
 
     private IObsClient obsClient;
 
-    @Override
-    public List<MailAttachment> getMailAttachment(Long mailInfoId, ReceivedEmail receivedEmail) {
-        List<EmailAttachment<? extends jakarta.activation.DataSource>> attachments = receivedEmail.attachments();
-
-        List<MailAttachment> mailAttachmentList = new ArrayList<>();
-        for (EmailAttachment<? extends jakarta.activation.DataSource> attachment : attachments) {
-
-            String name = attachment.getName();
-
-            ObsUpload obsUpload = new ObsUpload();
-            obsUpload.setFileName(name);
-            obsUpload.setBytes(attachment.toByteArray());
-
-            try {
-                R<JSONObject> jsonObjectR = obsClient.uploadHuaWei(obsUpload);
-                boolean success = jsonObjectR.isSuccess();
-                if (!success) {
-                    continue;
-                }
-                JSONObject data = jsonObjectR.getData();
-
-                MailAttachment mailAttachment = new MailAttachment();
-                mailAttachment.setName(name);
-                mailAttachment.setUrl(data.getString("path"));
-                mailAttachmentList.add(mailAttachment);
-
-            } catch (Exception e) {
-                throw new RuntimeException(e);
-            }
-
-        }
-
-        return mailAttachmentList;
-
-    }
+    // @Override
+    // public List<MailAttachment> getMailAttachment(Long mailInfoId, ReceivedEmail receivedEmail) {
+    //     List<EmailAttachment<? extends DataSource>> attachments = receivedEmail.attachments();
+    //
+    //     List<MailAttachment> mailAttachmentList = new ArrayList<>();
+    //     for (EmailAttachment<? extends DataSource> attachment : attachments) {
+    //
+    //         String name = attachment.getName();
+    //
+    //         ObsUpload obsUpload = new ObsUpload();
+    //         obsUpload.setFileName(name);
+    //         obsUpload.setBytes(attachment.toByteArray());
+    //
+    //         try {
+    //             R<JSONObject> jsonObjectR = obsClient.uploadHuaWei(obsUpload);
+    //             boolean success = jsonObjectR.isSuccess();
+    //             if (!success) {
+    //                 continue;
+    //             }
+    //             JSONObject data = jsonObjectR.getData();
+    //
+    //             MailAttachment mailAttachment = new MailAttachment();
+    //             mailAttachment.setName(name);
+    //             mailAttachment.setUrl(data.getString("path"));
+    //             mailAttachmentList.add(mailAttachment);
+    //
+    //         } catch (Exception e) {
+    //             throw new RuntimeException(e);
+    //         }
+    //
+    //     }
+    //
+    //     return mailAttachmentList;
+    //
+    // }
 }

+ 0 - 92
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/MailInfoServiceImpl.java

@@ -1,27 +1,12 @@
 package com.fjhx.service.impl;
 
-import cn.hutool.core.util.ObjectUtil;
-import com.baomidou.mybatisplus.core.toolkit.IdWorker;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
-import com.fjhx.entity.MailFolder;
 import com.fjhx.entity.MailInfo;
-import com.fjhx.enums.MailFlagEnum;
 import com.fjhx.mapper.MailInfoMapper;
-import com.fjhx.service.MailFolderService;
 import com.fjhx.service.MailInfoService;
-import com.fjhx.utils.mail.EmailAddress;
-import com.fjhx.utils.mail.ReceivedEmail;
-import jakarta.mail.Flags;
 import lombok.AllArgsConstructor;
-import org.springblade.core.tool.utils.StringPool;
 import org.springframework.stereotype.Service;
 
-import javax.mail.internet.MimeUtility;
-import java.io.UnsupportedEncodingException;
-import java.util.Date;
-import java.util.Map;
-import java.util.StringJoiner;
-
 /**
  * <p>
  * 邮件主表 服务实现类
@@ -34,82 +19,5 @@ import java.util.StringJoiner;
 @AllArgsConstructor
 public class MailInfoServiceImpl extends ServiceImpl<MailInfoMapper, MailInfo> implements MailInfoService {
 
-    private final MailFolderService mailFolderService;
-
-    @Override
-    public MailInfo getMailInfo(String mailboxId, Map<String, Long> folderMap, ReceivedEmail receivedEmail) {
-
-        String flags = getFlags(receivedEmail.flags());
-        String folderName = receivedEmail.originalMessage().getFolder().getFullName();
-
-        Long folderId = getFolderId(folderMap, folderName, mailboxId);
-
-        String fromEmail = null;
-        String fromPersonalName = null;
-
-        EmailAddress from = receivedEmail.from();
-        if (from != null) {
-            fromEmail = from.getEmail();
-            String personalName = from.getPersonalName();
-            if (ObjectUtil.isNotEmpty(personalName)) {
-                try {
-                    fromPersonalName = MimeUtility.decodeText(personalName);
-                } catch (UnsupportedEncodingException e) {
-                    throw new RuntimeException(e);
-                }
-            }
-        }
-
-        MailInfo mailInfo = new MailInfo();
-        mailInfo.setId(IdWorker.getId());
-        mailInfo.setMailboxId(mailboxId);
-        mailInfo.setMessageId(receivedEmail.messageId());
-        mailInfo.setMessageNumber(receivedEmail.messageNumber());
-        mailInfo.setSubject(receivedEmail.subject());
-        mailInfo.setFlags(flags);
-        mailInfo.setFolderId(folderId);
-        mailInfo.setFolderName(folderName);
-        mailInfo.setFromEmail(fromEmail);
-        mailInfo.setFromPersonalName(fromPersonalName);
-        mailInfo.setSendDate(receivedEmail.receivedDate());
-        mailInfo.setCreateTime(new Date());
-
-        return mailInfo;
-    }
-
-    private String getFlags(Flags flags) {
-        if (flags == null) {
-            return StringPool.EMPTY;
-        }
-
-
-        Flags.Flag[] systemFlags = flags.getSystemFlags();
-        if (systemFlags.length == 0) {
-            return StringPool.EMPTY;
-        }
-
-        StringJoiner stringJoiner = new StringJoiner(",");
-        for (Flags.Flag systemFlag : systemFlags) {
-            stringJoiner.add(MailFlagEnum.getType(systemFlag));
-        }
-        return stringJoiner.toString();
-    }
-
-    /**
-     * 获取区邮箱id
-     */
-    private Long getFolderId(Map<String, Long> mailFolderMap, String folderName, String mailboxId) {
-        Long folderId = mailFolderMap.get(folderName);
-        if (folderId != null) {
-            return folderId;
-        }
-
-        MailFolder mailFolder = new MailFolder();
-        mailFolder.setName(folderName);
-        mailFolder.setMailboxId(mailboxId);
-        mailFolderService.save(mailFolder);
-
-        return mailFolder.getId();
-    }
 
 }

+ 0 - 21
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/MailMessageServiceImpl.java

@@ -4,13 +4,8 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.fjhx.entity.MailMessage;
 import com.fjhx.mapper.MailMessageMapper;
 import com.fjhx.service.MailMessageService;
-import com.fjhx.utils.mail.EmailMessage;
-import com.fjhx.utils.mail.ReceivedEmail;
 import org.springframework.stereotype.Service;
 
-import java.util.ArrayList;
-import java.util.List;
-
 /**
  * <p>
  * 邮件正文 服务实现类
@@ -22,21 +17,5 @@ import java.util.List;
 @Service
 public class MailMessageServiceImpl extends ServiceImpl<MailMessageMapper, MailMessage> implements MailMessageService {
 
-    @Override
-    public List<MailMessage> getMailMessage(Long mailInfoId, ReceivedEmail receivedEmail) {
-
-        List<EmailMessage> messages = receivedEmail.messages();
-        List<MailMessage> mailMessageList = new ArrayList<>();
-
-        for (EmailMessage message : messages) {
-            MailMessage mailMessage = new MailMessage();
-            mailMessage.setMailInfoId(mailInfoId);
-            mailMessage.setMimeType(message.getMimeType());
-            mailMessage.setContent(message.getContent());
-            mailMessage.setEncoding(message.getEncoding());
-            mailMessageList.add(mailMessage);
-        }
 
-        return mailMessageList;
-    }
 }

+ 79 - 0
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/EmailUtil.java

@@ -0,0 +1,79 @@
+package com.fjhx.utils;
+
+import com.baomidou.mybatisplus.core.toolkit.IdWorker;
+import com.fjhx.entity.MailFolder;
+import com.fjhx.enums.MailFlagEnum;
+import com.sun.mail.imap.IMAPFolder;
+import com.sun.mail.imap.IMAPStore;
+import org.springblade.core.tool.utils.StringPool;
+
+import javax.mail.Flags;
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.StringJoiner;
+
+public class EmailUtil {
+
+    private static final Properties props = new Properties();
+
+    static {
+        props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
+    }
+
+    /**
+     * 获取store
+     */
+    public static IMAPStore getIMAPStore(String host, String user, String password) throws MessagingException {
+        Session session = Session.getInstance(props);
+        IMAPStore store = (IMAPStore) session.getStore("imap");
+        store.connect(host, 993, user, password);
+        return store;
+    }
+
+    /**
+     * 生成文件夹实体对象
+     */
+    public static List<MailFolder> createMailFolderList(IMAPStore store, String mailboxId) throws MessagingException {
+        IMAPFolder folder = (IMAPFolder) store.getDefaultFolder();
+        IMAPFolder[] folders = (IMAPFolder[]) folder.list();
+        List<MailFolder> mailFolderList = new ArrayList<>();
+        addMailFolderList(mailFolderList, folders, mailboxId);
+        return mailFolderList;
+    }
+
+    public static String getFlags(Flags flags) {
+        if (flags == null) {
+            return StringPool.EMPTY;
+        }
+
+        Flags.Flag[] systemFlags = flags.getSystemFlags();
+        if (systemFlags.length == 0) {
+            return StringPool.EMPTY;
+        }
+
+        StringJoiner stringJoiner = new StringJoiner(",");
+        for (Flags.Flag systemFlag : systemFlags) {
+            stringJoiner.add(MailFlagEnum.getType(systemFlag));
+        }
+        return stringJoiner.toString();
+    }
+
+    private static void addMailFolderList(List<MailFolder> mailFolderList, IMAPFolder[] folders, String mailboxId) throws MessagingException {
+        for (IMAPFolder folder : folders) {
+            int type = folder.getType();
+            if (type == 2) {
+                addMailFolderList(mailFolderList, (IMAPFolder[]) folder.list(), mailboxId);
+            } else if (type == 3) {
+                MailFolder mailFolder = new MailFolder();
+                mailFolder.setId(IdWorker.getId());
+                mailFolder.setMailboxId(mailboxId);
+                mailFolder.setName(folder.getFullName());
+                mailFolderList.add(mailFolder);
+            }
+        }
+    }
+
+}

+ 0 - 809
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/CommonEmail.java

@@ -1,809 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.activation.DataSource;
-import jakarta.mail.Address;
-import jakarta.mail.Header;
-import jodd.net.MimeTypes;
-import jodd.util.ArraysUtil;
-
-import java.util.*;
-
-/**
- * Common stuff for both {@link Email} and {@link ReceivedEmail}.
- */
-public abstract class CommonEmail<T extends CommonEmail<T>> {
-
-    public static final String X_PRIORITY = "X-Priority";
-    public static final int PRIORITY_HIGHEST = 1;
-    public static final int PRIORITY_HIGH = 2;
-    public static final int PRIORITY_NORMAL = 3;
-    public static final int PRIORITY_LOW = 4;
-    public static final int PRIORITY_LOWEST = 5;
-    /**
-     * All messages.
-     */
-    private final List<EmailMessage> messages = new ArrayList<>();
-    /**
-     * All headers.
-     */
-    private final Map<String, String> headers = new HashMap<>();
-
-    // ---------------------------------------------------------------- from
-    private final List<EmailAttachment<? extends DataSource>> attachments = new ArrayList<>();
-    /**
-     * FROM address.
-     */
-    private EmailAddress from;
-    /**
-     * TO address.
-     */
-    private EmailAddress[] to = EmailAddress.EMPTY_ARRAY;
-    private EmailAddress[] replyTo = EmailAddress.EMPTY_ARRAY;
-    /**
-     * CC address.
-     */
-    private EmailAddress[] cc = EmailAddress.EMPTY_ARRAY;
-    /**
-     * Message subject.
-     */
-    private String subject;
-
-    // ---------------------------------------------------------------- to
-    /**
-     * Message subject encoding.
-     */
-    private String subjectEncoding;
-    /**
-     * Email's sent date.
-     */
-    private Date sentDate;
-
-    @SuppressWarnings("unchecked")
-    protected T _this() {
-        return (T) this;
-    }
-
-    /**
-     * Clones the email with all its necessary data.
-     *
-     * @return new object of type T
-     */
-    @Override
-    public abstract T clone();
-
-    /**
-     * Sets the FROM address.
-     *
-     * @param from {@link EmailAddress}.
-     * @return this
-     */
-    public T from(final EmailAddress from) {
-        this.from = from;
-        return _this();
-    }
-
-    /**
-     * Sets the FROM address from {@link Address}.
-     *
-     * @param from {@link Address}
-     * @return this
-     * @see #from(EmailAddress)
-     */
-    public T from(final Address from) {
-        return from(EmailAddress.of(from));
-    }
-
-    /**
-     * Sets the FROM address.
-     *
-     * @param from Address may be specified with personal name like this: {@code Jenny Doe <email@foo.com>}.
-     * @return this
-     * @see #from(EmailAddress)
-     */
-    public T from(final String from) {
-        return from(EmailAddress.of(from));
-    }
-
-    /**
-     * Sets the FROM address by providing personal name and address.
-     *
-     * @param personalName personal name.
-     * @param from         email address.
-     * @return this
-     * @see #from(EmailAddress)
-     */
-    public T from(final String personalName, final String from) {
-        return from(new EmailAddress(personalName, from));
-    }
-
-    /**
-     * Returns FROM {@link EmailAddress}.
-     */
-    public EmailAddress from() {
-        return from;
-    }
-
-    /**
-     * Appends TO address.
-     *
-     * @param to {@link EmailAddress} to add.
-     * @return this
-     */
-    public T to(final EmailAddress to) {
-        this.to = ArraysUtil.append(this.to, to);
-        return _this();
-    }
-
-    // ---------------------------------------------------------------- reply-to
-
-    /**
-     * Appends TO address.
-     *
-     * @param to Address may be specified with personal name like this: {@code Jenny Doe <email@foo.com>}.
-     * @return this
-     * @see #to(EmailAddress)
-     */
-    public T to(final String to) {
-        return to(EmailAddress.of(to));
-    }
-
-    /**
-     * Appends TO address by personal name and email address.
-     *
-     * @param personalName personal name.
-     * @param to           email address.
-     * @return this
-     * @see #to(EmailAddress)
-     */
-    public T to(final String personalName, final String to) {
-        return to(new EmailAddress(personalName, to));
-    }
-
-    /**
-     * Appends TO address from {@code Address}.
-     *
-     * @param to {@link Address} to add.
-     * @return this
-     * @see #to(EmailAddress)
-     */
-    public T to(final Address to) {
-        return to(EmailAddress.of(to));
-    }
-
-    /**
-     * Appends one or more TO address.
-     *
-     * @param tos Address may be specified with personal name like this: {@code Jenny Doe <email@foo.com>}.
-     * @return this
-     * @see #to(EmailAddress...)
-     */
-    public T to(final String... tos) {
-        return to(EmailAddress.of(tos));
-    }
-
-    /**
-     * Appends one or more TO addresses.
-     *
-     * @param tos array of {@link Address}s to set.
-     * @return this
-     * @see #to(EmailAddress...)
-     */
-    public T to(final Address... tos) {
-        return to(EmailAddress.of(tos));
-    }
-
-    /**
-     * Appends TO addresses.
-     *
-     * @param tos vararg of {@link EmailAddress}es to set.
-     * @return this
-     */
-    public T to(final EmailAddress... tos) {
-        this.to = valueOrEmptyArray(tos);
-        return _this();
-    }
-
-    /**
-     * Returns TO addresses.
-     */
-    public EmailAddress[] to() {
-        return to;
-    }
-
-    /**
-     * Resets TO addresses.
-     */
-    public T resetTo() {
-        this.to = EmailAddress.EMPTY_ARRAY;
-        return _this();
-    }
-
-    /**
-     * Appends REPLY-TO address.
-     *
-     * @param replyTo {@link EmailAddress} to add.
-     * @return this
-     */
-    public T replyTo(final EmailAddress replyTo) {
-        this.replyTo = ArraysUtil.append(this.replyTo, replyTo);
-        return _this();
-    }
-
-    /**
-     * Appends REPLY-TO address.
-     *
-     * @param replyTo Address may be specified with personal name like this: {@code Jenny Doe <email@foo.com>}.
-     * @return this
-     * @see #replyTo(EmailAddress)
-     */
-    public T replyTo(final String replyTo) {
-        return replyTo(EmailAddress.of(replyTo));
-    }
-
-    // ---------------------------------------------------------------- cc
-
-    /**
-     * Appends REPLY-TO address.
-     *
-     * @param personalName personal name.
-     * @param replyTo      email address.
-     * @return this
-     * @see #replyTo(EmailAddress)
-     */
-    public T replyTo(final String personalName, final String replyTo) {
-        return replyTo(new EmailAddress(personalName, replyTo));
-    }
-
-    /**
-     * Appends REPLY-TO address.
-     *
-     * @param replyTo {@link Address} to add.
-     * @return this
-     * @see #replyTo(EmailAddress)
-     */
-    public T replyTo(final Address replyTo) {
-        return replyTo(EmailAddress.of(replyTo));
-    }
-
-    /**
-     * Appends one or more REPLY-TO address.
-     *
-     * @param replyTos array of {@link EmailAddress}es to set.
-     * @return this
-     * @see #replyTo(EmailAddress...)
-     */
-    public T replyTo(final String... replyTos) {
-        return replyTo(EmailAddress.of(replyTos));
-    }
-
-    /**
-     * Appeds one or more REPLY-TO address.
-     *
-     * @param replyTos array of {@link Address}es to set.
-     * @return this
-     * @see #replyTo(EmailAddress...)
-     */
-    public T replyTo(final Address... replyTos) {
-        return replyTo(EmailAddress.of(replyTos));
-    }
-
-    /**
-     * Appends REPLY-TO addresses.
-     *
-     * @param replyTo vararg of {@link EmailAddress}es to set.
-     * @return this
-     */
-    public T replyTo(final EmailAddress... replyTo) {
-        this.replyTo = ArraysUtil.join(this.replyTo, valueOrEmptyArray(replyTo));
-        return _this();
-    }
-
-    /**
-     * Returns REPLY-TO addresses.
-     */
-    public EmailAddress[] replyTo() {
-        return replyTo;
-    }
-
-    /**
-     * Resets all REPLY-To addresses.
-     */
-    public T resetReplyTo() {
-        this.replyTo = EmailAddress.EMPTY_ARRAY;
-        return _this();
-    }
-
-    /**
-     * Appends CC address.
-     *
-     * @param to {@link EmailAddress} to add.
-     * @return this
-     */
-    public T cc(final EmailAddress to) {
-        this.cc = ArraysUtil.append(this.cc, to);
-        return _this();
-    }
-
-    /**
-     * Appends CC address.
-     *
-     * @param cc Address may be specified with personal name like this: {@code Jenny Doe <email@foo.com>}.
-     * @return this
-     * @see #cc(EmailAddress)
-     */
-    public T cc(final String cc) {
-        return cc(EmailAddress.of(cc));
-    }
-
-    /**
-     * Appends CC address.
-     *
-     * @param personalName personal name.
-     * @param cc           email address.
-     * @return this
-     * @see #cc(EmailAddress)
-     */
-    public T cc(final String personalName, final String cc) {
-        return cc(new EmailAddress(personalName, cc));
-    }
-
-    // ---------------------------------------------------------------- subject
-
-    /**
-     * Appends CC address.
-     *
-     * @param cc {@link Address} to add.
-     * @return this
-     * @see #cc(EmailAddress)
-     */
-    public T cc(final Address cc) {
-        return cc(EmailAddress.of(cc));
-    }
-
-    /**
-     * Sets one or more CC address.
-     *
-     * @param ccs array of {@link String}s to set.
-     * @return this
-     * @see #cc(EmailAddress...)
-     */
-    public T cc(final String... ccs) {
-        return cc(EmailAddress.of(ccs));
-    }
-
-    /**
-     * Sets one or more CC address.
-     *
-     * @param ccs array of {@link Address}s to set.
-     * @return this
-     * @see #cc(EmailAddress...)
-     */
-    public T cc(final Address... ccs) {
-        return cc(EmailAddress.of(ccs));
-    }
-
-    /**
-     * Appends CC addresses.
-     *
-     * @param ccs vararg of {@link EmailAddress}es to set.
-     * @return this
-     */
-    public T cc(final EmailAddress... ccs) {
-        this.cc = ArraysUtil.join(this.cc, valueOrEmptyArray(ccs));
-        return _this();
-    }
-
-    /**
-     * Returns CC addresses.
-     */
-    public EmailAddress[] cc() {
-        return cc;
-    }
-
-    /**
-     * Resets all CC addresses.
-     */
-    public T resetCc() {
-        this.cc = EmailAddress.EMPTY_ARRAY;
-        return _this();
-    }
-
-    // ---------------------------------------------------------------- message
-
-    /**
-     * Sets message subject.
-     *
-     * @param subject The message subject to set.
-     * @return this
-     */
-    public T subject(final String subject) {
-        this.subject = subject;
-        return _this();
-    }
-
-    /**
-     * Sets message subject with specified encoding to override default platform encoding.
-     * If the subject contains non US-ASCII characters, it will be encoded using the specified charset.
-     * If the subject contains only US-ASCII characters, no encoding is done and it is used as-is.
-     * The application must ensure that the subject does not contain any line breaks.
-     *
-     * @param subject  The message subject
-     * @param encoding The encoding for the message subject.
-     * @return this
-     */
-    public T subject(final String subject, final String encoding) {
-        subject(subject);
-        this.subjectEncoding = encoding;
-        return _this();
-    }
-
-    /**
-     * Returns message subject.
-     *
-     * @return message subject.
-     */
-    public String subject() {
-        return this.subject;
-    }
-
-    /**
-     * Returns the message subject encoding.
-     *
-     * @return the message subject encoding.
-     */
-    public String subjectEncoding() {
-        return this.subjectEncoding;
-    }
-
-    /**
-     * Returns all messages.
-     */
-    public List<EmailMessage> messages() {
-        return messages;
-    }
-
-    /**
-     * Adds multiple messages.
-     *
-     * @param msgsToAdd {@link List} of {@link EmailMessage}s to add.
-     * @return this
-     */
-    public T message(final List<EmailMessage> msgsToAdd) {
-        messages.addAll(msgsToAdd);
-        return _this();
-    }
-
-    /**
-     * Adds an {@link EmailMessage}.
-     *
-     * @param msgToAdd {@link EmailMessage} to add.
-     * @return this
-     */
-    public T message(final EmailMessage msgToAdd) {
-        messages.add(msgToAdd);
-        return _this();
-    }
-
-    /**
-     * Adds a {@link EmailMessage}.
-     *
-     * @param text     The text to add as a {@link String}.
-     * @param mimeType The MIME type as a {@link String}.
-     * @param encoding The encoding as a {@link String}.
-     * @return this
-     * @see #message(EmailMessage)
-     */
-    public T message(final String text, final String mimeType, final String encoding) {
-        return message(new EmailMessage(text, mimeType, encoding));
-    }
-
-    /**
-     * Adds a {@link EmailMessage}.
-     *
-     * @param text     The text to add as a {@link String}.
-     * @param mimeType The MIME type as a {@link String}.
-     * @return this
-     * @see #message(EmailMessage)
-     */
-    public T message(final String text, final String mimeType) {
-        return message(new EmailMessage(text, mimeType));
-    }
-
-    /**
-     * Adds plain message text.
-     *
-     * @param text The text to add as a {@link String}.
-     * @return this
-     * @see #message(String, String)
-     */
-    public T textMessage(final String text) {
-        return message(text, MimeTypes.MIME_TEXT_PLAIN);
-    }
-
-    // ---------------------------------------------------------------- headers
-
-    /**
-     * Adds plain message text.
-     *
-     * @param text     The text to add as a {@link String}.
-     * @param encoding The encoding as a {@link String}.
-     * @return this
-     * @see #message(EmailMessage)
-     */
-    public T textMessage(final String text, final String encoding) {
-        return message(new EmailMessage(text, MimeTypes.MIME_TEXT_PLAIN, encoding));
-    }
-
-    /**
-     * Adds HTML message.
-     *
-     * @param html The HTML to add as a {@link String}.
-     * @return this
-     * @see #message(EmailMessage)
-     */
-    public T htmlMessage(final String html) {
-        return message(new EmailMessage(html, MimeTypes.MIME_TEXT_HTML));
-    }
-
-    /**
-     * Adds HTML message.
-     *
-     * @param html     The HTML to add as a {@link String}.
-     * @param encoding The encoding as a {@link String}.
-     * @return this
-     * @see #message(EmailMessage)
-     */
-    public T htmlMessage(final String html, final String encoding) {
-        return message(new EmailMessage(html, MimeTypes.MIME_TEXT_HTML, encoding));
-    }
-
-    /**
-     * Returns all headers as a {@link HashMap}.
-     *
-     * @return all headers in a {@link HashMap}
-     */
-    protected Map<String, String> headers() {
-        return headers;
-    }
-
-    /**
-     * Sets header value.
-     *
-     * @param name  The name of the header.
-     * @param value The value of the header.
-     * @return this
-     */
-    public T header(final String name, final String value) {
-        headers.put(name, value);
-        return _this();
-    }
-
-    /**
-     * Sets headers.
-     *
-     * @param headersToSet Headers to set.
-     * @return this
-     */
-    public T headers(final Map<String, String> headersToSet) {
-        headers.putAll(headersToSet);
-        return _this();
-    }
-
-    /**
-     * Sets headers.
-     *
-     * @param headersToSet Headers to set.
-     * @return this
-     * @see #header(String, String)
-     */
-    public T headers(final Enumeration<Header> headersToSet) {
-        while (headersToSet.hasMoreElements()) {
-            final Header header = headersToSet.nextElement();
-            header(header.getName(), header.getValue());
-        }
-        return _this();
-    }
-
-    /**
-     * Returns the value of a header.
-     *
-     * @param name The name of the header.
-     * @return The value of the header.
-     */
-    public String header(final String name) {
-        return headers.get(name);
-    }
-
-    // ---------------------------------------------------------------- attachments
-
-    /**
-     * Sets email priority.
-     *
-     * @param priority - Values of 1 through 5 are acceptable, with 1 being the highest priority, 3 = normal
-     *                 and 5 = lowest priority.
-     */
-    public T priority(final int priority) {
-        header(X_PRIORITY, String.valueOf(priority));
-        return _this();
-    }
-
-    /**
-     * Returns emails priority (1 - 5) or <code>-1</code> if priority not available.
-     *
-     * @see #priority(int)
-     */
-    public int priority() {
-        try {
-            return Integer.parseInt(headers.get(X_PRIORITY));
-        } catch (final NumberFormatException ignore) {
-            return -1;
-        }
-    }
-
-    /**
-     * Returns the list of all {@link EmailAttachment}s.
-     *
-     * @return List of {@link EmailAttachment}s. Returns empty list if no attachment is available.
-     */
-    public List<EmailAttachment<? extends DataSource>> attachments() {
-        return attachments;
-    }
-
-    /**
-     * Adds {@link EmailAttachment}s.
-     *
-     * @param attachments {@link List} of {@link EmailAttachment}s to add.
-     * @return this
-     */
-    protected T storeAttachments(final List<EmailAttachment<? extends DataSource>> attachments) {
-        this.attachments.addAll(attachments);
-        return _this();
-    }
-
-    /**
-     * Adds {@link EmailAttachment}.
-     *
-     * @param attachment {@link EmailAttachment} to add.
-     * @return this
-     */
-    protected T storeAttachment(final EmailAttachment<? extends DataSource> attachment) {
-        this.attachments.add(attachment);
-        return _this();
-    }
-
-    /**
-     * Adds {@link EmailAttachment}s.
-     *
-     * @param attachments {@link List} of {@link EmailAttachment}s to add.
-     * @return this
-     */
-    public T attachments(final List<EmailAttachment<? extends DataSource>> attachments) {
-        for (final EmailAttachment<?> attachment : attachments) {
-            attachment(attachment);
-        }
-        return _this();
-    }
-
-    /**
-     * Adds {@link EmailAttachment}. Content ID will be set to {@code null}.
-     *
-     * @param attachment {@link EmailAttachment} to add.
-     * @return this
-     */
-    public T attachment(final EmailAttachment<? extends DataSource> attachment) {
-        attachment.setContentId(null);
-        return storeAttachment(attachment);
-    }
-
-    /**
-     * @see #attachment(EmailAttachment)
-     */
-    public T attachment(final EmailAttachmentBuilder builder) {
-        return attachment(builder.buildByteArrayDataSource());
-    }
-
-    /**
-     * Attaches the embedded attachment: Content ID will be set if missing from attachment's file name.
-     *
-     * @param builder {@link EmailAttachmentBuilder}
-     * @return this
-     * @see #embeddedAttachment(EmailAttachment)
-     */
-    public T embeddedAttachment(final EmailAttachmentBuilder builder) {
-        builder.setContentIdFromNameIfMissing();
-
-        // https://github.com/oblac/jodd/issues/546
-        // https://github.com/oblac/jodd/issues/404#issuecomment-297011351
-        // content disposition will be set to "inline"
-        builder.inline(true);
-
-        return embeddedAttachment(builder.buildByteArrayDataSource());
-    }
-
-    // ---------------------------------------------------------------- date
-
-    /**
-     * Embed {@link EmailAttachment} to last message. No header is changed.
-     *
-     * @param attachment {@link EmailAttachment}
-     * @return this
-     * @see #storeAttachment(EmailAttachment)
-     */
-    public T embeddedAttachment(final EmailAttachment<? extends DataSource> attachment) {
-        storeAttachment(attachment);
-
-        final List<EmailMessage> messages = messages();
-        final int size = messages.size();
-        if (size > 1) {
-            // Add to last message
-            final int lastMessagePos = size - 1;
-            final EmailMessage lastMessage = messages.get(lastMessagePos);
-            attachment.setEmbeddedMessage(lastMessage);
-        }
-
-        return _this();
-    }
-
-    /**
-     * Sets email's sent date.
-     *
-     * @param date - Email's sent date. If {@code null}, then date will be set during the process of sending.
-     * @return this
-     */
-    public T sentDate(final Date date) {
-        sentDate = date;
-        return _this();
-    }
-
-
-    /**
-     * Returns email's sent date. If return value is {@code null}, then date
-     * will be set during the process of sending.
-     *
-     * @return email's sent date or {@code null} if it will be set later.
-     */
-    public Date sentDate() {
-        return sentDate;
-    }
-
-    // ---------------------------------------------------------------- toString
-
-    @Override
-    public String toString() {
-        return "Email{'" + from() + "\', subject='" + subject() + "\'}";
-    }
-
-    // ---------------------------------------------------------------- helper
-
-    protected EmailAddress[] valueOrEmptyArray(EmailAddress[] arr) {
-        if (arr == null) {
-            arr = EmailAddress.EMPTY_ARRAY;
-        }
-        return arr;
-    }
-}

+ 0 - 129
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EMLComposer.java

@@ -1,129 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.*;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-public class EMLComposer extends EMLProperties<EMLComposer> {
-
-    public static EMLComposer create() {
-        return new EMLComposer();
-    }
-
-    /**
-     * Creates EML string from given {@link Email}.
-     *
-     * @param email {@link Email} from which to create EML {@link String}.
-     * @return {@link String} with EML content.
-     */
-    public String compose(final Email email) {
-        if (getSession() == null) {
-            createSession(getProperties());
-        }
-
-        final OutputStreamTransport ost = new OutputStreamTransport(getSession());
-
-        final SendMailSession sendMailSession = new SendMailSession(getSession(), ost);
-
-        sendMailSession.sendMail(email);
-
-        return ost.getEml();
-    }
-
-
-    /**
-     * Creates EML string from given {@link ReceivedEmail}.
-     *
-     * @param receivedEmail {@link ReceivedEmail} from which to create EML {@link String}.
-     * @return {@link String} with EML content.
-     */
-    public String compose(final ReceivedEmail receivedEmail) {
-        Message msg = receivedEmail.originalMessage();
-
-        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
-
-        try {
-            msg.writeTo(outputStream);
-        } catch (IOException | MessagingException e) {
-            throw new MailException(e);
-        }
-
-        return outputStream.toString();
-    }
-
-
-    /**
-     * Special transport that writes message into the {@link OutputStream}.
-     */
-    private static class OutputStreamTransport extends Transport {
-
-        /**
-         * String with EML content.
-         */
-        private String eml;
-
-        /**
-         * Creates a new {@link OutputStreamTransport}.
-         *
-         * @param session {@link Session}.
-         */
-        public OutputStreamTransport(final Session session) {
-            super(session, new URLName("JODD_MAIL_2_EML", null, -1, null, null, null));
-        }
-
-        /**
-         * Sends a message.
-         *
-         * @param msg       {@link Message} to send.
-         * @param addresses array of {@link Address}es to send to.
-         */
-        @Override
-        public void sendMessage(final Message msg, final Address[] addresses) {
-            final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
-
-            try {
-                msg.writeTo(outputStream);
-            } catch (IOException | MessagingException e) {
-                throw new MailException(e);
-            }
-
-            eml = outputStream.toString();
-        }
-
-        /**
-         * Returns the EML content.
-         *
-         * @return EML content.
-         */
-        public String getEml() {
-            return eml;
-        }
-    }
-}

+ 0 - 126
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EMLParser.java

@@ -1,126 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.MessagingException;
-import jakarta.mail.Session;
-import jakarta.mail.internet.MimeMessage;
-import jodd.io.IOUtil;
-
-import java.io.*;
-
-/**
- * Developer-friendly class for parsing EML files.
- */
-public class EMLParser extends EMLProperties<EMLParser> {
-
-    public static EMLParser create() {
-        return new EMLParser();
-    }
-
-    /**
-     * Parses EML with provided EML content.
-     *
-     * @param emlContent {@link String} with EML content.
-     * @param charset    String with charset.
-     * @return {@link ReceivedEmail}.
-     * @throws UnsupportedEncodingException if the named charset is not supported.
-     * @throws MessagingException           if {@link MimeMessage} cannot be created.
-     * @see #parse(byte[])
-     */
-    public ReceivedEmail parse(final String emlContent, final String charset) throws
-            UnsupportedEncodingException, MessagingException {
-
-        final byte[] bytes = emlContent.getBytes(charset);
-        return parse(bytes);
-    }
-
-    /**
-     * Parses EML with provided EML content.
-     *
-     * @param emlContent {@link String} with EML content.
-     * @return {@link ReceivedEmail}.
-     * @throws MessagingException if {@link MimeMessage} cannot be created.
-     * @see #parse(String, String)
-     */
-    public ReceivedEmail parse(final String emlContent) throws MessagingException {
-        try {
-            return parse(emlContent, "UTF-8");
-        } catch (final UnsupportedEncodingException ignore) {
-            return null;
-        }
-    }
-
-    /**
-     * Parses EML with provided EML content.
-     *
-     * @param content byte[] with EML content.
-     * @return {@link ReceivedEmail}.
-     * @throws MessagingException if {@link MimeMessage} cannot be created.
-     * @see #parse(InputStream)
-     */
-    public ReceivedEmail parse(final byte[] content) throws MessagingException {
-        return parse(new ByteArrayInputStream(content));
-    }
-
-    /**
-     * Starts EML parsing with provided EML {@link File}.
-     *
-     * @param emlFile {@link File} with EML content.
-     * @return {@link ReceivedEmail}.
-     * @throws FileNotFoundException if emlFile cannot be found
-     * @throws MessagingException    if {@link MimeMessage} cannot be created.
-     * @see #parse(InputStream)
-     */
-    public ReceivedEmail parse(final File emlFile) throws FileNotFoundException, MessagingException {
-        final FileInputStream fileInputStream = new FileInputStream(emlFile);
-        try {
-            return parse(fileInputStream);
-        } finally {
-            IOUtil.close(fileInputStream);
-        }
-    }
-
-    /**
-     * Parses the EML content. If {@link Session} is not created, default one will be used.
-     *
-     * @param emlContentInputStream {@link InputStream} containing the EML content.
-     * @return {@link ReceivedEmail}.
-     * @throws MessagingException if {@link MimeMessage} cannot be created.
-     */
-    protected ReceivedEmail parse(final InputStream emlContentInputStream) throws MessagingException {
-        if (getSession() == null) {
-            createSession(getProperties());
-        }
-
-        try {
-            final MimeMessage message = new MimeMessage(getSession(), emlContentInputStream);
-            return new ReceivedEmail(message, false, null);
-        } finally {
-            IOUtil.close(emlContentInputStream);
-        }
-    }
-}

+ 0 - 131
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EMLProperties.java

@@ -1,131 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-package com.fjhx.utils.mail;
-
-import jakarta.mail.Session;
-
-import java.util.Properties;
-
-abstract class EMLProperties<T extends EMLProperties<T>> {
-
-    /**
-     * Custom {@link Properties}.
-     */
-    private final Properties properties = new Properties();
-    /**
-     * {@link Properties}.
-     */
-    private Session session;
-
-    @SuppressWarnings("unchecked")
-    protected T _this() {
-        return (T) this;
-    }
-
-    /**
-     * Returns the {@link Session}.
-     *
-     * @return the {@link Session}.
-     */
-    protected Session getSession() {
-        return session;
-    }
-
-    /**
-     * Returns the {@link Properties}.
-     *
-     * @return the {@link Properties}.
-     */
-    protected Properties getProperties() {
-        return properties;
-    }
-
-    /**
-     * Creates new {@link Session} with or without custom {@link Properties}.
-     *
-     * @param properties Custom properties to be used during {@link Session} creation. It is acceptable is this value is {@code null}.
-     * @return {@link Session} with any custom {@link Properties}
-     */
-    protected Session createSession(Properties properties) {
-        if (properties == null) {
-            properties = System.getProperties();
-        }
-
-        this.session = Session.getInstance(properties);
-
-        return session;
-    }
-
-    /**
-     * Copies properties from given set. If {@link Session} is already created, exception will be thrown.
-     *
-     * @param properties {@link Properties} to set.
-     * @return this
-     * @throws MailException if the {@link Properties} has already been set.
-     */
-    public T set(final Properties properties) throws MailException {
-        checkSessionNotSet();
-        this.properties.putAll(properties);
-        return _this();
-    }
-
-    /**
-     * Sets property for the {@link Session}. If {@link Session} is already created, an exception
-     * will be thrown.
-     *
-     * @param name  Property name to set.
-     * @param value Property value to set.
-     * @return this
-     * @throws MailException if the {@link Properties} has already been set.
-     */
-    public T set(final String name, final String value) {
-        checkSessionNotSet();
-        properties.setProperty(name, value);
-        return _this();
-    }
-
-    /**
-     * Uses default {@link Session}. Any property will be ignored.
-     *
-     * @return this
-     * @see System#getProperties()
-     */
-    public T useDefaultSession() {
-        this.session = Session.getDefaultInstance(System.getProperties());
-        return _this();
-    }
-
-    /**
-     * Ensures that {@link Session} has not yet been set.
-     *
-     * @throws MailException if {@link Session} has already been set.
-     */
-    private void checkSessionNotSet() throws MailException {
-        if (session != null) {
-            throw new MailException("Can't set properties after session is assigned");
-        }
-    }
-
-}

+ 0 - 185
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/Email.java

@@ -1,185 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.Address;
-import jodd.util.ArraysUtil;
-
-import java.util.Date;
-
-/**
- * E-mail holds all parts of an email and handle attachments.
- */
-public class Email extends CommonEmail<Email> {
-
-    /**
-     * BCC address.
-     */
-    private EmailAddress[] bcc = EmailAddress.EMPTY_ARRAY;
-
-    /**
-     * Static constructor for fluent interface.
-     */
-    public static Email create() {
-        return new Email();
-    }
-
-    // ---------------------------------------------------------------- date
-
-    @Override
-    public Email clone() {
-        return create()
-
-                // from / reply-to
-                .from(from())
-                .replyTo(replyTo())
-
-                // recipients
-                .to(to())
-                .cc(cc())
-                .bcc(bcc())
-
-                // subject
-                .subject(subject(), subjectEncoding())
-
-                // dates
-                .sentDate(sentDate())
-
-                // headers - includes priority
-                .headers(headers())
-
-                // content / attachments
-                .storeAttachments(attachments())
-                .message(messages());
-    }
-
-    // ---------------------------------------------------------------- bcc
-
-    /**
-     * Sets current date as the sent date.
-     *
-     * @return this
-     * @see #sentDate(Date)
-     */
-    public Email currentSentDate() {
-        return sentDate(new Date());
-    }
-
-    /**
-     * Appends BCC address.
-     *
-     * @param to {@link EmailAddress} to add.
-     * @return this
-     */
-    public Email bcc(final EmailAddress to) {
-        this.bcc = ArraysUtil.append(this.bcc, to);
-        return _this();
-    }
-
-    /**
-     * Appends BCC address.
-     *
-     * @param bcc Address may be specified with personal name like this: {@code Jenny Doe <email@foo.com>}.
-     * @return this
-     * @see #bcc(EmailAddress)
-     */
-    public Email bcc(final String bcc) {
-        return bcc(EmailAddress.of(bcc));
-    }
-
-    /**
-     * Appends BCC address.
-     *
-     * @param personalName personal name.
-     * @param bcc          email address.
-     * @return this
-     * @see #bcc(EmailAddress)
-     */
-    public Email bcc(final String personalName, final String bcc) {
-        return bcc(new EmailAddress(personalName, bcc));
-    }
-
-    /**
-     * Appends BCC address.
-     *
-     * @param bcc {@link Address} to add.
-     * @return this
-     * @see #bcc(EmailAddress)
-     */
-    public Email bcc(final Address bcc) {
-        return bcc(EmailAddress.of(bcc));
-    }
-
-    /**
-     * Appends BCC address.
-     *
-     * @param bccs array of {@link String}s to set.
-     * @return this
-     * @see #bcc(EmailAddress...)
-     */
-    public Email bcc(final String... bccs) {
-        return bcc(EmailAddress.of(bccs));
-    }
-
-    /**
-     * Appends BCC address.
-     *
-     * @param bccs array of {@link Address}es to set.
-     * @return this
-     * @see #bcc(EmailAddress...)
-     */
-    public Email bcc(final Address... bccs) {
-        return bcc(EmailAddress.of(bccs));
-    }
-
-    /**
-     * Appends one or more BCC addresses.
-     *
-     * @param bccs vararg of {@link EmailAddress}es to set.
-     * @return this
-     */
-    public Email bcc(final EmailAddress... bccs) {
-        this.bcc = ArraysUtil.join(this.bcc, valueOrEmptyArray(bccs));
-        return _this();
-    }
-
-    /**
-     * Returns BCC addresses.
-     */
-    public EmailAddress[] bcc() {
-        return bcc;
-    }
-
-    /**
-     * Resets BCC addresses.
-     */
-    public Email resetBcc() {
-        this.bcc = EmailAddress.EMPTY_ARRAY;
-        return _this();
-    }
-
-
-}

+ 0 - 233
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailAddress.java

@@ -1,233 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.Address;
-import jakarta.mail.MessagingException;
-import jakarta.mail.internet.AddressException;
-import jakarta.mail.internet.InternetAddress;
-import jodd.util.StringUtil;
-
-import java.io.UnsupportedEncodingException;
-
-/**
- * Storage for personal name and email address.
- * Serves as an email address adapter between various formats.
- */
-public class EmailAddress {
-
-    public static final EmailAddress[] EMPTY_ARRAY = new EmailAddress[0];
-
-    /**
-     * Email address.
-     */
-    private final String email;
-
-    /**
-     * Personal name.
-     */
-    private final String personalName;
-
-    /**
-     * Creates new address by specifying email and personal name.
-     *
-     * @param personalName personal name.
-     * @param email        email address.
-     */
-    public EmailAddress(final String personalName, final String email) {
-        this.email = email;
-        this.personalName = personalName;
-    }
-
-    /**
-     * @see #EmailAddress(String, String)
-     */
-    public static EmailAddress of(final String personalName, final String email) {
-        return new EmailAddress(personalName, email);
-    }
-
-    /**
-     * Creates new address by specifying one of the following:
-     * <ul>
-     * <li>{@code "foo@bar.com" - only email address.}</li>
-     * <li>{@code "Jenny Doe &lt;foo@bar.com&gt;" - first part of the string is personal name,
-     * and the other part is email, surrounded with < and >.}</li>
-     * </ul>
-     *
-     * @param address {@link String} containing address to convert.
-     */
-    public static EmailAddress of(String address) {
-        address = address.trim();
-
-        if (!StringUtil.endsWithChar(address, '>')) {
-            return new EmailAddress(null, address);
-        }
-
-        final int ndx = address.lastIndexOf('<');
-        if (ndx == -1) {
-            return new EmailAddress(null, address);
-        }
-
-        String email = address.substring(ndx + 1, address.length() - 1);
-        String personalName = address.substring(0, ndx).trim();
-        return new EmailAddress(personalName, email);
-    }
-
-    /**
-     * Creates new email address from {@link InternetAddress}.
-     *
-     * @param internetAddress {@link InternetAddress} to convert
-     */
-    public static EmailAddress of(final InternetAddress internetAddress) {
-        return new EmailAddress(internetAddress.getPersonal(), internetAddress.getAddress());
-    }
-
-    /**
-     * Creates new email address from {@link InternetAddress}.
-     *
-     * @param address {@link Address} to convert.
-     */
-    public static EmailAddress of(final Address address) {
-        return of(address.toString());
-    }
-
-    // ---------------------------------------------------------------- getters
-
-    /**
-     * Converts array of {@link Address} to {@link EmailAddress}.
-     *
-     * @param addresses array of {@link Address}es to convert.
-     * @return an array of {@link EmailAddress}.
-     */
-    public static EmailAddress[] of(final Address... addresses) {
-        if (addresses == null) {
-            return EmailAddress.EMPTY_ARRAY;
-        }
-        if (addresses.length == 0) {
-            return EmailAddress.EMPTY_ARRAY;
-        }
-
-        final EmailAddress[] res = new EmailAddress[addresses.length];
-
-        for (int i = 0; i < addresses.length; i++) {
-            res[i] = EmailAddress.of(addresses[i]);
-        }
-
-        return res;
-    }
-
-    /**
-     * Converts array of {@link String} to {@link EmailAddress}.
-     *
-     * @param addresses array of {@link String}s to convert.
-     * @return an array of {@link EmailAddress}.
-     */
-    public static EmailAddress[] of(final String... addresses) {
-        if (addresses == null) {
-            return EmailAddress.EMPTY_ARRAY;
-        }
-        if (addresses.length == 0) {
-            return EmailAddress.EMPTY_ARRAY;
-        }
-
-        final EmailAddress[] res = new EmailAddress[addresses.length];
-
-        for (int i = 0; i < addresses.length; i++) {
-            res[i] = EmailAddress.of(addresses[i]);
-        }
-
-        return res;
-    }
-
-    /**
-     * Convert from array of {@link EmailAddress} to array of {@link InternetAddress}.
-     *
-     * @param addresses {@link EmailMessage}
-     * @return array of {@link InternetAddress}. Returns empty array if addresses was {@code null}.
-     * @throws MessagingException if there are failures
-     */
-    public static InternetAddress[] convert(final EmailAddress[] addresses) throws MessagingException {
-        if (addresses == null) {
-            return new InternetAddress[0];
-        }
-
-        final int numRecipients = addresses.length;
-        final InternetAddress[] address = new InternetAddress[numRecipients];
-
-        for (int i = 0; i < numRecipients; i++) {
-            address[i] = addresses[i].toInternetAddress();
-        }
-        return address;
-    }
-
-    // ---------------------------------------------------------------- convert
-
-    /**
-     * Returns email address.
-     *
-     * @return email address.
-     */
-    public String getEmail() {
-        return email;
-    }
-
-    // ---------------------------------------------------------------- arrays
-
-    /**
-     * Returns personal name.
-     *
-     * @return personal name. Value may be {@code null}.
-     */
-    public String getPersonalName() {
-        return personalName;
-    }
-
-    /**
-     * Returns string representation of this.
-     *
-     * @return String representation of this.
-     */
-    @Override
-    public String toString() {
-        if (this.personalName == null) {
-            return this.email;
-        }
-        return this.personalName + " <" + this.email + '>';
-    }
-
-    /**
-     * Creates new {@link InternetAddress} from current data.
-     *
-     * @return {@link InternetAddress} from current data.
-     */
-    public InternetAddress toInternetAddress() throws AddressException {
-        try {
-            return new InternetAddress(email, personalName, "UTF-8");
-        } catch (final UnsupportedEncodingException ueex) {
-            throw new AddressException(ueex.toString());
-        }
-    }
-}

+ 0 - 296
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailAttachment.java

@@ -1,296 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.activation.DataSource;
-import jakarta.mail.internet.MimeUtility;
-import jodd.io.IOUtil;
-
-import java.io.*;
-
-/**
- * Email attachment.
- */
-public class EmailAttachment<T extends DataSource> {
-
-    /**
-     * {@link String} with file name.
-     */
-    private final String name;
-    /**
-     * {@link DataSource} of the attachment.
-     */
-    private final T dataSource;
-    /**
-     * Content ID of attachment.
-     */
-    private String contentId;
-    /**
-     * Whether the attachment is inline.
-     */
-    private boolean isInline;
-    /**
-     * Target {@link EmailMessage}.
-     */
-    private EmailMessage targetMessage;
-
-    // ---------------------------------------------------------------- constructor
-    /**
-     * Size of attachment. Defaults to -1.
-     */
-    private int size = -1;
-
-    /**
-     * Creates new attachment with given name and content id for inline attachments.
-     *
-     * @param contentId Value may be {@code null} if attachment is not embedded.
-     * @param isInline  {@code true} if the attachment is inline.
-     * @param name      Email name may be {@code null} as well.
-     * @see MimeUtility#decodeText(String)
-     */
-    protected EmailAttachment(final String name, final String contentId, final boolean isInline, final T dataSource) {
-        if (name != null) {
-            try {
-                this.name = MimeUtility.decodeText(name);
-            } catch (final UnsupportedEncodingException useexc) {
-                throw new MailException(useexc);
-            }
-        } else {
-            this.name = null;
-        }
-        this.contentId = contentId;
-        this.isInline = isInline;
-        this.dataSource = dataSource;
-    }
-
-    // ---------------------------------------------------------------- properties
-
-    /**
-     * Returns new/empty {@link EmailAttachmentBuilder}.
-     *
-     * @return {@link EmailAttachmentBuilder}.
-     */
-    public static EmailAttachmentBuilder with() {
-        return new EmailAttachmentBuilder();
-    }
-
-    /**
-     * Returns attachment name.
-     *
-     * @return attachment name. Value may be {@code null}.
-     */
-    public String getName() {
-        return name;
-    }
-
-    /**
-     * Returns encoded attachment name.
-     *
-     * @return encoded attachment name. Value may be {@code null}.
-     */
-    public String getEncodedName() {
-        if (name == null) {
-            return null;
-        }
-        try {
-            return MimeUtility.encodeText(name);
-        } catch (final UnsupportedEncodingException ueex) {
-            throw new MailException(ueex);
-        }
-    }
-
-    /**
-     * Returns content id for inline attachments.
-     * <p>
-     * Value is {@code null} when attachment is not embedded.
-     *
-     * @return content id for inline attachments
-     * @see #isEmbedded()
-     */
-    public String getContentId() {
-        return contentId;
-    }
-
-    /**
-     * Sets content ID.
-     *
-     * @param contentId content ID of {@link EmailAttachment}.
-     * @return this
-     */
-    protected EmailAttachment<T> setContentId(final String contentId) {
-        this.contentId = contentId;
-        return this;
-    }
-
-    /**
-     * Returns {@code true} if the attachment is embedded.
-     * <p>
-     * Embedded attachment is one when {@link #getContentId()} is not {@code null}.
-     *
-     * @return {@code true} if the attachment is embedded.
-     */
-    public boolean isEmbedded() {
-        return contentId != null;
-    }
-
-    /**
-     * Returns {@code true} if it is an inline attachment.
-     *
-     * @return {@code true} if it is an inline attachment.
-     */
-    public boolean isInline() {
-        return isInline;
-    }
-
-    /**
-     * Sets whether attachment is inline.
-     *
-     * @param isInline {@code true} for inline.
-     * @return this
-     */
-    protected EmailAttachment<T> setInline(final boolean isInline) {
-        this.isInline = isInline;
-        return this;
-    }
-
-    /**
-     * Sets target message for embedded attachments.
-     *
-     * @param emailMessage target {@link EmailMessage}.
-     */
-    public EmailAttachment<T> setEmbeddedMessage(final EmailMessage emailMessage) {
-        targetMessage = emailMessage;
-        return this;
-    }
-
-    // ---------------------------------------------------------------- data source
-
-    /**
-     * Returns {@code true} if attachment is embedded into provided message.
-     *
-     * @param emailMessage target {@link EmailMessage}.
-     * @return {@code true} if attachment is embedded into provided message.
-     */
-    public boolean isEmbeddedInto(final EmailMessage emailMessage) {
-        return targetMessage == emailMessage;
-    }
-
-    /**
-     * Returns {@link DataSource} implementation, depending on attachment source.
-     */
-    public T getDataSource() {
-        return dataSource;
-    }
-
-    // ---------------------------------------------------------------- size
-
-    /**
-     * Returns content type of {@link DataSource}.
-     *
-     * @return content type of {@link DataSource}.
-     */
-    public String getContentType() {
-        return dataSource.getContentType();
-    }
-
-    /**
-     * Returns size of attachment.
-     *
-     * @return size of attachment or -1 if not yet calculated from {@link DataSource}.
-     */
-    public int getSize() {
-        return size;
-    }
-
-    /**
-     * Sets size of attachment.
-     *
-     * @param size the size of the attachment.
-     * @return this
-     */
-    protected EmailAttachment<T> setSize(final int size) {
-        this.size = size;
-        return this;
-    }
-
-    // ---------------------------------------------------------------- content methods
-
-    /**
-     * Returns byte content of the attachment.
-     *
-     * @return byte array with content of the attachment.
-     */
-    public byte[] toByteArray() {
-        final ByteArrayOutputStream out;
-        if (size != -1) {
-            out = new ByteArrayOutputStream(size);
-        } else {
-            out = new ByteArrayOutputStream();
-        }
-        writeToStream(out);
-        return out.toByteArray();
-    }
-
-    /**
-     * Saves attachment to a file.
-     *
-     * @param destination The destination file to be written.
-     */
-    public void writeToFile(final File destination) {
-        InputStream input = null;
-        OutputStream output = null;
-        try {
-            input = getDataSource().getInputStream();
-            output = new FileOutputStream(destination);
-
-            IOUtil.copy(input, output);
-        } catch (final IOException ioex) {
-            throw new MailException(ioex);
-        } finally {
-            IOUtil.close(input);
-            IOUtil.close(output);
-        }
-    }
-
-    /**
-     * Saves attachment to the output stream.
-     *
-     * @param out OutputStream where attachment should be copied to.
-     */
-    public void writeToStream(final OutputStream out) {
-        InputStream input = null;
-        try {
-            input = getDataSource().getInputStream();
-
-            IOUtil.copy(input, out);
-        } catch (final IOException ioex) {
-            throw new MailException(ioex);
-        } finally {
-            IOUtil.close(input);
-        }
-    }
-
-}

+ 0 - 288
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailAttachmentBuilder.java

@@ -1,288 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.activation.DataSource;
-import jakarta.activation.FileDataSource;
-import jakarta.mail.util.ByteArrayDataSource;
-import jodd.io.FileNameUtil;
-import jodd.io.FileUtil;
-import jodd.net.MimeTypes;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-
-import static com.fjhx.utils.mail.EmailUtil.NO_NAME;
-
-
-/**
- * Helper class for convenient {@link EmailAttachment} creation.
- */
-public class EmailAttachmentBuilder {
-
-    // ---------------------------------------------------------------- constructor
-
-    /**
-     * {@link String} with name of {@link EmailAttachment}.
-     */
-    private String name;
-
-    // ---------------------------------------------------------------- properties
-    /**
-     * Content ID of {@link EmailAttachment}.
-     */
-    private String contentId;
-    /**
-     * Whether the {@link EmailAttachment} is inline. Defaults to false.
-     */
-    private boolean isInline = false;
-    /**
-     * {@link DataSource} containing {@link EmailAttachment} content.
-     */
-    private DataSource dataSource;
-    /**
-     * Target {@link EmailMessage}.
-     */
-    private EmailMessage targetMessage;
-
-    /**
-     * Only allow instantiation from {@link EmailAttachment} class
-     */
-    protected EmailAttachmentBuilder() {
-    }
-
-    // ---------------------------------------------------------------- data
-
-    /**
-     * Sets file name.
-     *
-     * @param name File name to set.
-     * @return this
-     */
-    public EmailAttachmentBuilder name(final String name) {
-        if (name != null && !name.trim().isEmpty()) {
-            this.name = name;
-        }
-        return this;
-    }
-
-    /**
-     * Sets content ID.
-     *
-     * @param contentId content ID of {@link EmailAttachment}.
-     * @return this
-     */
-    public EmailAttachmentBuilder contentId(final String contentId) {
-        this.contentId = contentId;
-        return this;
-    }
-
-    /**
-     * Sets whether {@link EmailAttachment} is inline.
-     *
-     * @param isInline {@code true} for inline.
-     * @return this
-     */
-    public EmailAttachmentBuilder inline(final boolean isInline) {
-        this.isInline = isInline;
-        return this;
-    }
-
-    /**
-     * Sets target {@link EmailMessage}.
-     *
-     * @param targetMessage Target {@link EmailMessage}.
-     * @return this
-     */
-    public EmailAttachmentBuilder embeddedMessage(final EmailMessage targetMessage) {
-        this.targetMessage = targetMessage;
-        return this;
-    }
-
-    /**
-     * Sets the {@link DataSource}. Common {@link DataSource}s include {@link ByteArrayDataSource} and
-     * {@link FileDataSource}.
-     *
-     * @param dataSource {@link DataSource}
-     * @return this
-     */
-    public <T extends DataSource> EmailAttachmentBuilder content(final T dataSource) {
-        this.dataSource = dataSource;
-        name(dataSource.getName());
-        return this;
-    }
-
-    /**
-     * Creates new {@link ByteArrayDataSource} and then calls {@link #content(DataSource)}.
-     *
-     * @param inputStream {@link InputStream}
-     * @param contentType content type from {@link EmailAttachment}.
-     * @return this
-     * @throws IOException if {@link ByteArrayDataSource} cannot be created from {@link InputStream}
-     * @see #content(DataSource)
-     */
-    public EmailAttachmentBuilder content(final InputStream inputStream, final String contentType)
-            throws IOException {
-        return content(new ByteArrayDataSource(inputStream, resolveContentType(contentType)));
-    }
-
-    /**
-     * Creates new {@link ByteArrayDataSource} and then calls {@link #content(DataSource)}.
-     *
-     * @param bytes       array of bytes
-     * @param contentType content type from {@link EmailAttachment}.
-     * @return this
-     * @see #content(DataSource)
-     */
-    public EmailAttachmentBuilder content(final byte[] bytes, final String contentType) {
-        return content(new ByteArrayDataSource(bytes, resolveContentType(contentType)));
-    }
-
-    /**
-     * Uses {@code null} contentType.
-     *
-     * @see #content(byte[], String)
-     */
-    public EmailAttachmentBuilder content(final byte[] bytes) {
-        return content(bytes, null);
-    }
-
-    /**
-     * Creates new {@link FileDataSource} and then calls {@link #content(DataSource)}
-     *
-     * @param file {@link File}
-     * @return this
-     * @see #content(DataSource)
-     */
-    public EmailAttachmentBuilder content(final File file) {
-        return content(new FileDataSource(file));
-    }
-
-    /**
-     * @param fileName String representing file name.
-     * @return this
-     * @see #content(File)
-     */
-    public EmailAttachmentBuilder content(final String fileName) {
-        return content(new File(fileName));
-    }
-
-    // ---------------------------------------------------------------- factory/builder
-
-    /**
-     * Creates {@link EmailAttachment}.
-     *
-     * @return {@link EmailAttachment}.
-     * @throws MailException if issue with {@link DataSource}.
-     */
-    public EmailAttachment<ByteArrayDataSource> buildByteArrayDataSource() throws MailException {
-        try {
-            final ByteArrayDataSource bads;
-            if (dataSource instanceof ByteArrayDataSource) {
-                bads = (ByteArrayDataSource) dataSource;
-            } else {
-                bads = new ByteArrayDataSource(dataSource.getInputStream(), dataSource.getContentType());
-            }
-            checkDataSource();
-            return new EmailAttachment<>(name, contentId, isInline, bads).setEmbeddedMessage(targetMessage);
-        } catch (final IOException ioexc) {
-            throw new MailException(ioexc);
-        }
-    }
-
-    /**
-     * Creates {@link EmailAttachment}.
-     *
-     * @return {@link EmailAttachment}.
-     * @throws MailException if issue with {@link DataSource}.
-     */
-    public EmailAttachment<FileDataSource> buildFileDataSource(final String messageId, final File attachmentStorage) throws MailException {
-        try {
-            final FileDataSource fds;
-            if (dataSource instanceof FileDataSource) {
-                fds = (FileDataSource) dataSource;
-            } else {
-                final File file = new File(attachmentStorage, messageId);
-                FileUtil.writeStream(file, dataSource.getInputStream());
-                fds = new FileDataSource(file);
-            }
-            checkDataSource();
-            return new EmailAttachment<>(name, contentId, isInline, fds).setEmbeddedMessage(targetMessage);
-        } catch (final IOException ioexc) {
-            throw new MailException(ioexc);
-        }
-    }
-
-    /**
-     * Check to ensure {@link DataSource} ds is valid.
-     *
-     * @throws MailException if DataSource is {@code null}.
-     */
-    private void checkDataSource() {
-        if (dataSource == null) {
-            throw new MailException("dataSource must be valid. It can be set using #content().");
-        }
-    }
-
-    // ---------------------------------------------------------------- properties
-
-    /**
-     * Set content ID if it is missing.
-     *
-     * @return this
-     * @see #contentId(String)
-     */
-    protected EmailAttachmentBuilder setContentIdFromNameIfMissing() {
-        if (contentId == null) {
-            if (name != null) {
-                contentId(FileNameUtil.getName(name));
-            } else {
-                contentId(NO_NAME);
-            }
-        }
-        return this;
-    }
-
-    /**
-     * Resolves content type from all data.
-     *
-     * @param contentType Content type if we know it. {@code null} is fine to use.
-     * @return content type
-     */
-    protected String resolveContentType(final String contentType) {
-        if (contentType != null) {
-            return contentType;
-        }
-        if (name == null) {
-            return MimeTypes.MIME_APPLICATION_OCTET_STREAM;
-        }
-
-        final String extension = FileNameUtil.getExtension(name);
-        return MimeTypes.getMimeType(extension);
-    }
-
-}

+ 0 - 395
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailFilter.java

@@ -1,395 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.Flags;
-import jakarta.mail.Header;
-import jakarta.mail.Message;
-import jakarta.mail.search.*;
-
-import java.util.Date;
-
-/**
- * <code>EmailFilter</code> helps in building boolean queries of search terms.
- * There are two ways how it can be used, both can be combined.
- * <p>
- * First way is constructing boolean expression using <i>groups</i>.
- * Just use {@link #and(EmailFilter...)}, {@link #or(EmailFilter...)}
- * and {@link #not(EmailFilter)} methods that takes any number
- * of filters that will be joined with chosen boolean operator.
- * <p>
- * Second way is more fluent. It may not be used to express some
- * complex queries, but for every-day use it would be enough.
- * Use methods {@link #and()} and {@link #or()} to define
- * how <b>all next</b> terms will be joined. Method {@link #not()}
- * marks the <b>one next</b> term to be added as NOT term.
- */
-public class EmailFilter {
-
-    /**
-     * The {@link SearchTerm} to be used.
-     */
-    protected SearchTerm searchTerm;
-    boolean operatorAnd = true;
-    boolean nextIsNot;
-
-    /**
-     * Creates new Email filter.
-     */
-    public static EmailFilter filter() {
-        return new EmailFilter();
-    }
-
-    /**
-     * Defines filter for SUBJECT field.
-     *
-     * @param subject The SUBJECT.
-     * @return this
-     */
-    public EmailFilter subject(final String subject) {
-        final SearchTerm subjectTerm = new SubjectTerm(subject);
-        concat(subjectTerm);
-        return this;
-    }
-
-    /**
-     * Defines filter for message id.
-     *
-     * @param messageId The message ID.
-     * @return this
-     */
-    public EmailFilter messageId(final String messageId) {
-        final SearchTerm msgIdTerm = new MessageIDTerm(messageId);
-        concat(msgIdTerm);
-        return this;
-    }
-
-    /**
-     * Defines filteer for message number.
-     *
-     * @param messageNumber The message number.
-     * @return this
-     */
-    public EmailFilter messageNumber(final int messageNumber) {
-        final SearchTerm msgIdTerm = new MessageNumberTerm(messageNumber);
-        concat(msgIdTerm);
-        return this;
-    }
-
-    /**
-     * Defines filter for FROM field.
-     *
-     * @param fromAddress The FROM address
-     * @return this
-     */
-    public EmailFilter from(final String fromAddress) {
-        final SearchTerm fromTerm = new FromStringTerm(fromAddress);
-        concat(fromTerm);
-        return this;
-    }
-
-    /**
-     * Defines filter for TO field.
-     *
-     * @param toAddress The TO address.
-     * @return this
-     */
-    public EmailFilter to(final String toAddress) {
-        final SearchTerm toTerm = new RecipientStringTerm(Message.RecipientType.TO, toAddress);
-        concat(toTerm);
-        return this;
-    }
-
-    /**
-     * Defines filter for CC field.
-     *
-     * @param ccAddress CC addreses.
-     * @return this
-     */
-    public EmailFilter cc(final String ccAddress) {
-        final SearchTerm toTerm = new RecipientStringTerm(Message.RecipientType.CC, ccAddress);
-        concat(toTerm);
-        return this;
-    }
-
-    /**
-     * Defines filter for BCC field.
-     *
-     * @param bccAddress BCC address.
-     * @return this
-     */
-    public EmailFilter bcc(final String bccAddress) {
-        final SearchTerm toTerm = new RecipientStringTerm(Message.RecipientType.BCC, bccAddress);
-        concat(toTerm);
-        return this;
-    }
-
-    /**
-     * Defines filter for many flags at once.
-     *
-     * @param flags The {@link Flags} to filter on.
-     * @param value The flag setting to check for.
-     * @return this
-     */
-    public EmailFilter flags(final Flags flags, final boolean value) {
-        final SearchTerm flagTerm = new FlagTerm(flags, value);
-        concat(flagTerm);
-        return this;
-    }
-
-    /**
-     * Defines filter for single flag.
-     *
-     * @param flag  The flag to filter on.
-     * @param value The flag setting to check for.
-     * @return this
-     */
-    public EmailFilter flag(final Flags.Flag flag, final boolean value) {
-        final Flags flags = new Flags();
-        flags.add(flag);
-        return flags(flags, value);
-    }
-
-    /**
-     * Defines filter for received date.
-     *
-     * @return this
-     */
-    public EmailFilter receivedDate(final Operator operator, final long milliseconds) {
-        final SearchTerm term = new ReceivedDateTerm(operator.value, new Date(milliseconds));
-        concat(term);
-        return this;
-    }
-
-    /**
-     * Defines filter for sent date.
-     *
-     * @param operator     {@link Operator} to use.
-     * @param milliseconds the milliseconds since January 1, 1970, 00:00:00 GMT.
-     * @return this
-     */
-    public EmailFilter sentDate(final Operator operator, final long milliseconds) {
-        final SearchTerm term = new SentDateTerm(operator.value, new Date(milliseconds));
-        concat(term);
-        return this;
-    }
-
-    /**
-     * Defines filter on a message body.
-     * All parts of the message that are of MIME type "text/*" are searched.
-     *
-     * @param pattern String pattern use in body.
-     * @return this
-     */
-    public EmailFilter text(final String pattern) {
-        final SearchTerm term = new BodyTerm(pattern);
-        concat(term);
-        return this;
-    }
-
-    /**
-     * Defines filter for {@link Header}.
-     *
-     * @param headerName The name of the {@link Header}.
-     * @param pattern    String pattern to use for headerName.
-     * @return this
-     */
-    public EmailFilter header(final String headerName, final String pattern) {
-        final SearchTerm term = new HeaderTerm(headerName, pattern);
-        concat(term);
-        return this;
-    }
-
-    /**
-     * Defines filter for message size.
-     *
-     * @param comparison {@link Operator}.
-     * @param size       size of message.
-     * @return this
-     */
-    public EmailFilter size(final Operator comparison, final int size) {
-        final SearchTerm term = new SizeTerm(comparison.value, size);
-        concat(term);
-        return this;
-    }
-
-    /**
-     * Changes concatenation mode to AND.
-     *
-     * @return this
-     */
-    public EmailFilter and() {
-        this.operatorAnd = true;
-        return this;
-    }
-
-    // ---------------------------------------------------------------- boolean
-
-    /**
-     * Changes concatenation mode to OR.
-     *
-     * @return this
-     */
-    public EmailFilter or() {
-        this.operatorAnd = false;
-        return this;
-    }
-
-    /**
-     * Marks next condition to be NOT.
-     *
-     * @return this
-     */
-    public EmailFilter not() {
-        this.nextIsNot = true;
-        return this;
-    }
-
-    /**
-     * Defines AND group of filters.
-     *
-     * @param emailFilters array of {@link EmailFilter}s to AND.
-     * @return this
-     */
-    public EmailFilter and(final EmailFilter... emailFilters) {
-        final SearchTerm[] searchTerms = new SearchTerm[emailFilters.length];
-
-        for (int i = 0; i < emailFilters.length; i++) {
-            searchTerms[i] = emailFilters[i].searchTerm;
-        }
-
-        concat(new AndTerm(searchTerms));
-        return this;
-    }
-
-    /**
-     * Defines OR group of filters.
-     *
-     * @param emailFilters array of {@link EmailFilter}s to OR.
-     * @return this
-     */
-    public EmailFilter or(final EmailFilter... emailFilters) {
-        final SearchTerm[] searchTerms = new SearchTerm[emailFilters.length];
-
-        for (int i = 0; i < emailFilters.length; i++) {
-            searchTerms[i] = emailFilters[i].searchTerm;
-        }
-
-        concat(new OrTerm(searchTerms));
-        return this;
-    }
-
-    /**
-     * Appends single filter as NOT.
-     *
-     * @param emailFilter {@link EmailFilter} to append.
-     * @return this
-     */
-    public EmailFilter not(final EmailFilter emailFilter) {
-        final SearchTerm searchTerm = new NotTerm(emailFilter.searchTerm);
-        concat(searchTerm);
-        return this;
-    }
-
-    /**
-     * Concatenates last search term with new one.
-     *
-     * @param searchTerm searchTerm {@link SearchTerm} concatenate.
-     * @see #and(SearchTerm)
-     * @see #or(SearchTerm)
-     */
-    protected void concat(SearchTerm searchTerm) {
-        if (nextIsNot) {
-            searchTerm = new NotTerm(searchTerm);
-            nextIsNot = false;
-        }
-        if (operatorAnd) {
-            and(searchTerm);
-        } else {
-            or(searchTerm);
-        }
-    }
-
-    // ---------------------------------------------------------------- concat
-
-    /**
-     * Sets {@link AndTerm} as searchTerm.
-     *
-     * @param searchTerm {@link SearchTerm} to set as AND.
-     */
-    protected void and(final SearchTerm searchTerm) {
-        if (this.searchTerm == null) {
-            this.searchTerm = searchTerm;
-            return;
-        }
-
-        this.searchTerm = new AndTerm(this.searchTerm, searchTerm);
-    }
-
-    /**
-     * Sets {@link OrTerm} searchTerm.
-     *
-     * @param searchTerm {@link SearchTerm} to set as OR.
-     */
-    protected void or(final SearchTerm searchTerm) {
-        if (this.searchTerm == null) {
-            this.searchTerm = searchTerm;
-            return;
-        }
-
-        this.searchTerm = new OrTerm(this.searchTerm, searchTerm);
-    }
-
-    /**
-     * Returns search term.
-     *
-     * @return {@link SearchTerm}.
-     */
-    public SearchTerm getSearchTerm() {
-        return searchTerm;
-    }
-
-    // ---------------------------------------------------------------- term
-
-    /**
-     * Comparison operator.
-     */
-    public enum Operator {
-        EQ(jakarta.mail.search.ComparisonTerm.EQ),
-        GE(jakarta.mail.search.ComparisonTerm.GE),
-        GT(jakarta.mail.search.ComparisonTerm.GT),
-        LE(jakarta.mail.search.ComparisonTerm.LE),
-        LT(jakarta.mail.search.ComparisonTerm.LT),
-        NE(jakarta.mail.search.ComparisonTerm.NE);
-
-        private final int value;
-
-        Operator(final int value) {
-            this.value = value;
-        }
-    }
-
-}

+ 0 - 99
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailMessage.java

@@ -1,99 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-/**
- * Represents email message including the mime type and encoding.
- */
-public class EmailMessage {
-
-    /**
-     * The content as a {@link String}.
-     */
-    private final String content;
-
-    /**
-     * The MIME type as a as a {@link String}.
-     */
-    private final String mimeType;
-
-    /**
-     * The encoding as a {@link String}.
-     */
-    private final String encoding;
-
-    /**
-     * Defines email content.
-     *
-     * @param content  The content as a {@link String}.
-     * @param mimeType The MIME type as a as a {@link String}.
-     * @param encoding The encoding as a {@link String}.
-     */
-    public EmailMessage(final String content, final String mimeType, final String encoding) {
-        this.content = content;
-        this.mimeType = mimeType;
-        this.encoding = encoding;
-    }
-
-    /**
-     * Uses UTF-8 email content by default.
-     *
-     * @param content  The content as a {@link String}.
-     * @param mimeType The MIME type as a as a {@link String}.
-     */
-    public EmailMessage(final String content, final String mimeType) {
-        this(content, mimeType, "UTF-8");
-    }
-
-    // ---------------------------------------------------------------- getters
-
-    /**
-     * Returns message content.
-     *
-     * @return {@link String} containing the message content.
-     */
-    public String getContent() {
-        return content;
-    }
-
-    /**
-     * Returns message mime type.
-     *
-     * @return {@link String} containing the message mime type.
-     */
-    public String getMimeType() {
-        return mimeType;
-    }
-
-    /**
-     * Returns message encoding.
-     *
-     * @return {@link String} containing the message encoding.
-     */
-    public String getEncoding() {
-        return encoding;
-    }
-}

+ 0 - 222
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/EmailUtil.java

@@ -1,222 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.*;
-import jakarta.mail.internet.MimeBodyPart;
-import jakarta.mail.internet.MimeUtility;
-import jodd.util.CharUtil;
-import jodd.util.StringPool;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.util.Properties;
-import java.util.function.Consumer;
-
-/**
- * Email utilities.
- */
-public class EmailUtil {
-
-    protected static final String ATTR_CHARSET = "charset=";
-    static final String NO_NAME = "no-name";
-
-    /**
-     * Extracts MIME type from content type.
-     *
-     * @param contentType MIME type.
-     * @return MIME type for the given content type.
-     */
-    // TODO: should this always return lowercase or always uppercase?
-    public static String extractMimeType(final String contentType) {
-        final int ndx = contentType.indexOf(';');
-        final String mime;
-        if (ndx != -1) {
-            mime = contentType.substring(0, ndx);
-        } else {
-            mime = contentType;
-        }
-        return mime;
-    }
-
-    /**
-     * Extracts encoding from a given content type.
-     *
-     * @param contentType content type.
-     * @return Encoding from the content type. May return {@code null} if encoding is not specified in content type.
-     */
-    // TODO: should this always return lowercase or always uppercase?
-    public static String extractEncoding(final String contentType) {
-        int ndx = contentType.indexOf(';');
-        final String charset = ndx != -1 ? contentType.substring(ndx + 1) : StringPool.EMPTY;
-        String encoding = null;
-
-        ndx = charset.indexOf(ATTR_CHARSET);
-        if (ndx != -1) {
-            ndx += ATTR_CHARSET.length();
-            final int len = charset.length();
-
-            if (charset.charAt(ndx) == '"') {
-                ndx++;
-            }
-            final int start = ndx;
-
-            while (ndx < len) {
-                final char c = charset.charAt(ndx);
-                if ((c == '"') || (CharUtil.isWhitespace(c)) || (c == ';')) {
-                    break;
-                }
-                ndx++;
-            }
-            encoding = charset.substring(start, ndx);
-        }
-        return encoding;
-    }
-
-    /**
-     * Extracts encoding from a given content type.
-     *
-     * @param contentType     content type.
-     * @param defaultEncoding Default encoding to be used if extract returns {@code null}.
-     *                        If defaultEncoding is {@code null}, default encoding will be used.
-     * @return Encoding from the content type.
-     * @see #extractEncoding(String)
-     */
-    public static String extractEncoding(final String contentType, String defaultEncoding) {
-        String encoding = extractEncoding(contentType);
-
-        if (encoding == null) {
-            if (defaultEncoding == null) {
-                defaultEncoding = "UTF-8";
-            }
-            encoding = defaultEncoding;
-        }
-        return encoding;
-    }
-
-    /**
-     * Correctly resolves file name from the message part.
-     * Thanx to: Flavio Pompermaier
-     *
-     * @param part {@link Part} to decode file name from.
-     * @return String containing file name.
-     */
-    public static String resolveFileName(final Part part) throws MessagingException {
-        if (!(part instanceof MimeBodyPart)) {
-            return part.getFileName();
-        }
-
-        final String contentType = part.getContentType();
-        String ret;
-
-        try {
-            ret = MimeUtility.decodeText(part.getFileName());
-        } catch (final Exception ex) {
-            // String[] contentId = part.getHeader("Content-ID");
-            // if (contentId != null && contentId.length > 0) {
-            final String contentId = ((MimeBodyPart) part).getContentID();
-            if (contentId != null) {
-                ret = contentId + contentTypeForFileName(contentType);
-            } else {
-                ret = defaultFileName(contentType);
-            }
-        }
-
-        return ret;
-    }
-
-    private static String contentTypeForFileName(final String contentType) {
-        return StringPool.DOT + contentType.substring(contentType.lastIndexOf("/") + 1, contentType.length());
-    }
-
-    private static String defaultFileName(final String contentType) {
-        return NO_NAME + contentTypeForFileName(contentType);
-    }
-
-    /**
-     * @param protocol          Protocol such as {@link ImapServer#PROTOCOL_IMAP} or {@link Pop3Server#PROTOCOL_POP3}.
-     * @param sessionProperties Session properties to use.
-     * @param authenticator     Authenticator which contains necessary authentication for server.
-     * @param debugConsumer
-     * @return {@link ReceiveMailSession}.
-     */
-    public static ReceiveMailSession createSession(final String protocol, final Properties sessionProperties, final Authenticator authenticator, final File attachmentStorage, final Consumer<String> debugConsumer) {
-        final Session session = Session.getInstance(sessionProperties, authenticator);
-        if (debugConsumer != null) {
-            session.setDebugOut(new PrintStream(new ByteArrayOutputStream() {
-                @Override
-                public void flush() throws IOException {
-                    final String record;
-                    synchronized (this) {
-                        super.flush();
-                        record = this.toString().trim();
-                        super.reset();
-
-                        if (record.length() == 0 || record.equals(System.lineSeparator())) {
-                            // avoid empty records
-                            return;
-                        }
-
-                        debugConsumer.accept(record);
-                    }
-                }
-            }, true));
-        }
-        final Store store;
-        try {
-            store = session.getStore(protocol);
-        } catch (final NoSuchProviderException nspex) {
-            final String errMsg = String.format("Failed to create %s session", protocol);
-            throw new MailException(errMsg, nspex);
-        }
-        return new ReceiveMailSession(session, store, attachmentStorage);
-    }
-
-    /**
-     * Check whether flags is a empty flags
-     *
-     * @param flags a flags of message to check
-     * @return whether the flags is empty
-     */
-    public static boolean isEmptyFlags(final Flags flags) {
-        if (flags == null) {
-            return true;
-        }
-        final Flags.Flag[] systemFlags = flags.getSystemFlags();
-        if (systemFlags != null && systemFlags.length > 0) {
-            return false;
-        }
-        final String[] userFlags = flags.getUserFlags();
-        if (userFlags != null && userFlags.length > 0) {
-            return false;
-        }
-
-        return true;
-    }
-
-}

+ 0 - 99
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ImapServer.java

@@ -1,99 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.NoSuchProviderException;
-import jakarta.mail.Session;
-import jakarta.mail.Store;
-import jodd.util.StringPool;
-
-import java.util.Properties;
-
-/**
- * IMAP Server.
- */
-public class ImapServer extends MailServer<ReceiveMailSession> {
-
-    protected static final String PROTOCOL_IMAP = "imap";
-
-    /**
-     * Default IMAP port.
-     */
-    protected static final int DEFAULT_IMAP_PORT = 143;
-
-    public ImapServer(final Builder builder) {
-        super(builder, DEFAULT_IMAP_PORT);
-    }
-
-    protected ImapServer(final Builder builder, final int defaultPort) {
-        super(builder, defaultPort);
-    }
-
-
-    @Override
-    protected Properties createSessionProperties() {
-        final Properties props = super.createSessionProperties();
-
-        props.setProperty(MAIL_IMAP_HOST, host);
-        props.setProperty(MAIL_IMAP_PORT, String.valueOf(port));
-        props.setProperty(MAIL_IMAP_PARTIALFETCH, StringPool.FALSE);
-        props.setProperty(MAIL_IMAP_PEEK, StringPool.TRUE);
-
-        if (timeout > 0) {
-            final String timeoutValue = String.valueOf(timeout);
-            props.put(MAIL_IMAP_CONNECTIONTIMEOUT, timeoutValue);
-            props.put(MAIL_IMAP_TIMEOUT, timeoutValue);
-        }
-
-        return props;
-    }
-
-    /**
-     * Returns email store.
-     *
-     * @return IMAPStore
-     * @throws NoSuchProviderException if a provider for the given protocol is not found.
-     */
-    protected Store getStore(final Session session) throws NoSuchProviderException {
-        return session.getStore(PROTOCOL_IMAP);
-    }
-
-    /**
-     * {@inheritDoc}
-     *
-     * @return {@link ReceiveMailSession}
-     */
-    @Override
-    public ReceiveMailSession createSession() {
-        return EmailUtil.createSession(
-                PROTOCOL_IMAP,
-                createSessionProperties(),
-                authenticator,
-                attachmentStorage,
-                debugConsumer);
-    }
-
-}

+ 0 - 90
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ImapSslServer.java

@@ -1,90 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.PasswordAuthentication;
-import jakarta.mail.Session;
-import jakarta.mail.URLName;
-import jodd.util.StringPool;
-import org.eclipse.angus.mail.imap.IMAPSSLStore;
-
-import java.util.Properties;
-
-/**
- * IMAP SSL Server.
- */
-public class ImapSslServer extends ImapServer {
-
-    /**
-     * Default IMAP SSL port.
-     */
-    protected static final int DEFAULT_SSL_PORT = 993;
-
-    public ImapSslServer(final Builder builder) {
-        super(builder, DEFAULT_SSL_PORT);
-    }
-
-    @Override
-    protected Properties createSessionProperties() {
-        final Properties props = super.createSessionProperties();
-
-        props.setProperty(MAIL_IMAP_SOCKET_FACTORY_PORT, String.valueOf(port));
-        props.setProperty(MAIL_IMAP_SOCKET_FACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
-        props.setProperty(MAIL_IMAP_SOCKET_FACTORY_FALLBACK, StringPool.FALSE);
-
-        return props;
-    }
-
-    /**
-     * Returns email store.
-     *
-     * @param session {@link Session}
-     * @return {@link IMAPSSLStore}
-     */
-    @Override
-    protected IMAPSSLStore getStore(final Session session) {
-        final SimpleAuthenticator simpleAuthenticator = (SimpleAuthenticator) authenticator;
-
-        final URLName url;
-
-        if (simpleAuthenticator == null) {
-            url = new URLName(
-                    PROTOCOL_IMAP,
-                    host, port,
-                    StringPool.EMPTY, null, null);
-        } else {
-            final PasswordAuthentication pa = simpleAuthenticator.getPasswordAuthentication();
-            url = new URLName(
-                    PROTOCOL_IMAP,
-                    host, port,
-                    StringPool.EMPTY,
-                    pa.getUserName(), pa.getPassword());
-        }
-
-        return new IMAPSSLStore(session, url);
-    }
-
-}

+ 0 - 62
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/MailException.java

@@ -1,62 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jodd.exception.UncheckedException;
-
-/**
- * Jodd Mail exception.
- */
-public class MailException extends UncheckedException {
-
-    /**
-     * Creates a {@link MailException}.
-     *
-     * @param message Error message.
-     */
-    public MailException(final String message) {
-        super(message);
-    }
-
-    /**
-     * Creates a {@link MailException}.
-     *
-     * @param message Error message.
-     * @param t       {@link Throwable} which occurred.
-     */
-    public MailException(final String message, final Throwable t) {
-        super(message, t);
-    }
-
-    /**
-     * Creates a {@link MailException}.
-     *
-     * @param t {@link Throwable} which occurred.
-     */
-    public MailException(final Throwable t) {
-        super(t);
-    }
-}

+ 0 - 373
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/MailServer.java

@@ -1,373 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.Authenticator;
-import jakarta.mail.Session;
-
-import java.io.File;
-import java.util.Objects;
-import java.util.Properties;
-import java.util.function.Consumer;
-
-public abstract class MailServer<MailSessionImpl extends MailSession> {
-
-    // This is the list of all mail properties used by Jakarta Mail API and it's implementation, Angus.
-    // Jakarta: https://javaee.github.io/javamail/docs/api/
-    // Angus (smtp): https://github.com/eclipse-ee4j/angus-mail/blob/master/providers/smtp/src/main/java/org/eclipse/angus/mail/smtp/package-info.java
-    // Angus (imap): https://github.com/eclipse-ee4j/angus-mail/blob/master/providers/imap/src/main/java/org/eclipse/angus/mail/imap/package-info.java
-    // Angus (pop3): https://github.com/eclipse-ee4j/angus-mail/blob/master/providers/pop3/src/main/java/org/eclipse/angus/mail/pop3/package-info.java
-
-    public static final String MAIL_HOST = "mail.host";
-    public static final String MAIL_FROM = "mail.from";
-    public static final String MAIL_DEBUG = "mail.debug";
-    public static final String MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol";
-    public static final String MAIL_MIME_ADDRESS_STRICT = "mail.mime.address.strict";
-
-    public static final String MAIL_SMTP_HOST = "mail.smtp.host";
-    public static final String MAIL_SMTP_PORT = "mail.smtp.port";
-    public static final String MAIL_SMTP_USER = "mail.smtp.user";
-
-    public static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
-    public static final String MAIL_SMTP_FROM = "mail.smtp.from";
-    public static final String MAIL_SMTP_CONNECTIONTIMEOUT = "mail.smtp.connectiontimeout";
-    public static final String MAIL_SMTP_TIMEOUT = "mail.smtp.timeout";
-    public static final String MAIL_SMTP_WRITETIMEOUT = "mail.smtp.writetimeout";
-
-    public static final String MAIL_SMTP_STARTTLS_REQUIRED = "mail.smtp.starttls.required";
-    public static final String MAIL_SMTP_STARTTLS_ENABLE = "mail.smtp.starttls.enable";
-    public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "mail.smtp.socketFactory.port";
-    public static final String MAIL_SMTP_SOCKET_FACTORY_CLASS = "mail.smtp.socketFactory.class";
-    public static final String MAIL_SMTP_SOCKET_FACTORY_FALLBACK = "mail.smtp.socketFactory.fallback";
-
-
-    public static final String MAIL_IMAP_CONNECTIONTIMEOUT = "mail.imap.connectiontimeout";
-    public static final String MAIL_IMAP_TIMEOUT = "mail.imap.timeout";
-    public static final String MAIL_IMAP_PORT = "mail.imap.port";
-    public static final String MAIL_IMAP_HOST = "mail.imap.host";
-    public static final String MAIL_IMAP_USER = "mail.imap.user";
-    public static final String MAIL_IMAP_PARTIALFETCH = "mail.imap.partialfetch";
-    public static final String MAIL_IMAP_PEEK = "mail.imap.peek";
-
-    public static final String MAIL_IMAP_SOCKET_FACTORY_PORT = "mail.imap.socketFactory.port";
-    public static final String MAIL_IMAP_SOCKET_FACTORY_CLASS = "mail.imap.socketFactory.class";
-    public static final String MAIL_IMAP_SOCKET_FACTORY_FALLBACK = "mail.imap.socketFactory.fallback";
-
-    public static final String MAIL_POP3_PORT = "mail.pop3.port";
-    public static final String MAIL_POP3_HOST = "mail.pop3.host";
-    public static final String MAIL_POP3_USER = "mail.pop3.user";
-    public static final String MAIL_POP3_AUTH = "mail.pop3.auth";
-    public static final String MAIL_POP3_CONNECTIONTIMEOUT = "mail.pop3.connectiontimeout";
-    public static final String MAIL_POP3_TIMEOUT = "mail.pop3.timeout";
-
-    public static final String MAIL_POP3_SOCKET_FACTORY_PORT = "mail.pop3.socketFactory.port";
-    public static final String MAIL_POP3_SOCKET_FACTORY_CLASS = "mail.pop3.socketFactory.class";
-    public static final String MAIL_POP3_SOCKET_FACTORY_FALLBACK = "mail.pop3.socketFactory.fallback";
-
-    // NOT PART OF SPECIFICATION:
-
-    public static final String MAIL_EVENT_EXECUTOR = "mail.event.executor";
-    public static final String MAIL_EVENT_SCOPE = "mail.event.scope";
-    public static final String MAIL_DEBUG_AUTH = "mail.debug.auth";
-    public static final String MAIL_DEBUG_AUTH_USERNAME = "mail.debug.auth.username";
-    public static final String MAIL_DEBUG_AUTH_PASSWORD = "mail.debug.auth.password";
-
-    /**
-     * The host.
-     */
-    protected final String host;
-
-    /**
-     * The port.
-     */
-    protected final int port;
-
-    /**
-     * The {@link Authenticator}.
-     */
-    protected final Authenticator authenticator;
-
-    protected final File attachmentStorage;
-
-    protected final boolean debugMode;
-    protected final Consumer<String> debugConsumer;
-
-    /**
-     * Whether strict address checking is turned on.
-     */
-    protected final boolean strictAddress;
-
-    /**
-     * Connection timeout.
-     */
-    protected final int timeout;
-
-    protected final Properties customProperties;
-
-    /**
-     * {@link MailServer} defined with its host, port and {@link Authenticator}.
-     */
-    protected MailServer(final Builder builder, final int defaultPort) {
-        Objects.requireNonNull(builder.host, "Host cannot be null");
-
-        this.host = builder.host;
-        this.port = builder.port == -1 ? defaultPort : builder.port;
-        this.authenticator = builder.authenticator;
-        this.attachmentStorage = builder.attachmentStorage;
-        this.timeout = builder.timeout;
-        this.strictAddress = builder.strictAddress;
-        this.debugMode = builder.debug;
-        this.debugConsumer = builder.debugConsumer;
-        this.customProperties = builder.customProperties;
-    }
-
-    /**
-     * Returns new mail server builder.
-     */
-    public static Builder create() {
-        return new Builder();
-    }
-
-    /**
-     * Creates new mail session.
-     *
-     * @return {@link MailSession} or an implementing class such as {@link ReceiveMailSession}
-     * or {@link SendMailSession}. The {@link Session} properties must be set <b>before</b>
-     * the {@link Session} is created.
-     */
-    public abstract MailSessionImpl createSession();
-
-    /**
-     * Creates {@link MailSession} {@link Properties}.
-     *
-     * @return session {@link Properties}
-     */
-    protected Properties createSessionProperties() {
-        final Properties props = new Properties();
-
-        props.putAll(customProperties);
-
-        if (debugMode) {
-            props.put(MAIL_DEBUG, "true");
-        }
-
-        if (!strictAddress) {
-            props.put(MAIL_MIME_ADDRESS_STRICT, "false");
-        }
-
-        return props;
-    }
-
-    // ---------------------------------------------------------------- builder
-
-    /**
-     * Used to create implementing instances of {@link MailServer}.
-     *
-     * @see ImapServer
-     * @see ImapSslServer
-     * @see Pop3Server
-     * @see Pop3SslServer
-     * @see SmtpServer
-     * @see SmtpSslServer
-     */
-    public static class Builder {
-        private final Properties customProperties = new Properties();
-        private String host = null;
-        private int port = -1;
-        private boolean ssl = false;
-        private Authenticator authenticator;
-        private File attachmentStorage;
-        private boolean debug;
-        private Consumer<String> debugConsumer;
-        private int timeout = 0;
-        private boolean strictAddress = true;
-
-        /**
-         * Sets the host.
-         *
-         * @param host The host to set.
-         * @return this
-         */
-        public Builder host(final String host) {
-            this.host = host;
-            return this;
-        }
-
-        /**
-         * Sets the port.
-         *
-         * @param port The port to set.
-         * @return this
-         */
-        public Builder port(final int port) {
-            this.port = port;
-            return this;
-        }
-
-        /**
-         * Sets the SSL implementation of the Mail server.
-         *
-         * @param ssl SSL flag
-         * @return this
-         */
-        public Builder ssl(final boolean ssl) {
-            this.ssl = ssl;
-            return this;
-        }
-
-        /**
-         * Defines attachment storage, a folder where attachments will be saved.
-         */
-        public Builder storeAttachmentsIn(final File attachmentStorage) {
-            this.attachmentStorage = attachmentStorage;
-            return this;
-        }
-
-        /**
-         * Sets authenticator as {@link SimpleAuthenticator} using username and password.
-         *
-         * @param username The username to use.
-         * @param password The password to use.
-         * @return this
-         */
-        public Builder auth(final String username, final String password) {
-            Objects.requireNonNull(username, "Username cannot be null");
-            Objects.requireNonNull(password, "Password cannot be null");
-
-            return auth(new SimpleAuthenticator(username, password));
-        }
-
-        /**
-         * Sets the authenticator.
-         *
-         * @param authenticator {@link Authenticator} to set.
-         * @return this
-         */
-        public Builder auth(final Authenticator authenticator) {
-            this.authenticator = authenticator;
-            return this;
-        }
-
-        /**
-         * Enable or disable debug mode.
-         *
-         * @param debug {@code true} to turn on debugging. By default, this is {@code false}.
-         * @return this
-         */
-        public Builder debugMode(final boolean debug) {
-            this.debug = debug;
-            return this;
-        }
-
-        /**
-         * Set debug consumer
-         *
-         * @param consumer a String consumer to be called for debug logging. By default, this is null.
-         * @return this
-         */
-        public Builder debugConsumer(final Consumer<String> consumer) {
-            this.debugConsumer = consumer;
-            return this;
-        }
-
-        /**
-         * Defines timeout value in milliseconds for all mail-related operations.
-         *
-         * @param timeout timeout value in milliseconds.
-         * @return this
-         */
-        public Builder timeout(final int timeout) {
-            this.timeout = timeout;
-            return this;
-        }
-
-        /**
-         * Disables the strict address.
-         *
-         * @param strictAddress {@code true} if strict address checking should be turned on. By default, this is {@code true}.
-         * @return this
-         */
-        public Builder strictAddress(final boolean strictAddress) {
-            this.strictAddress = strictAddress;
-            return this;
-        }
-
-        /**
-         * Specifies a custom property.
-         */
-        public Builder property(final String name, final String value) {
-            this.customProperties.put(name, value);
-            return this;
-        }
-
-        /**
-         * Specifies a non-string custom property; such as `mail.event.executor`.
-         */
-        public Builder property(final String name, final Object value) {
-            this.customProperties.put(name, value);
-            return this;
-        }
-
-        // ---------------------------------------------------------------- build
-
-        /**
-         * Create a {@link ImapServer} from current data.
-         *
-         * @return {@link ImapServer} from current data.
-         */
-        public ImapServer buildImapMailServer() {
-            if (ssl) {
-                return new ImapSslServer(this);
-            }
-            return new ImapServer(this);
-        }
-
-        /**
-         * Create a {@link Pop3Server} from current data.
-         *
-         * @return {@link Pop3Server} from current data.
-         */
-        public Pop3Server buildPop3MailServer() {
-            if (ssl) {
-                return new Pop3SslServer(this);
-            }
-            return new Pop3Server(this);
-        }
-
-        /**
-         * Create a {@link SmtpServer} from current data.
-         *
-         * @return {@link SmtpServer} from current data.
-         */
-        public SmtpServer buildSmtpMailServer() {
-            if (ssl) {
-                return new SmtpSslServer(this);
-            }
-            return new SmtpServer(this);
-        }
-
-    }
-}

+ 0 - 123
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/MailSession.java

@@ -1,123 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-
-import jakarta.mail.*;
-import jakarta.mail.internet.MimeUtility;
-
-/**
- * Mail session base.
- */
-abstract class MailSession<T extends Service> implements AutoCloseable {
-
-    protected final Service service;
-    private final Session session;
-
-    /**
-     * Creates new mail session.
-     *
-     * @param session {@link Session}.
-     * @param service {@link Service} such as {@link Store} or {@link Transport}.
-     */
-    protected MailSession(final Session session, final Service service) {
-        this.session = session;
-        this.service = service;
-    }
-
-    /**
-     * Setups the system email properties.
-     */
-    protected static void setupSystemMailProperties() {
-        System.setProperty("mail.mime.encodefilename", Boolean.valueOf(Defaults.mailMimeEncodefilename).toString());
-        System.setProperty("mail.mime.decodefilename", Boolean.valueOf(Defaults.mailMimeDecodefilename).toString());
-    }
-
-    /**
-     * Opens session.
-     */
-    public void open() {
-        try {
-            service.connect();
-        } catch (final MessagingException msex) {
-            throw new MailException("Open session error", msex);
-        }
-    }
-
-    /**
-     * Closes session.
-     */
-    @Override
-    public void close() {
-        try {
-            service.close();
-        } catch (final MessagingException mex) {
-            throw new MailException("Failed to close session", mex);
-        }
-    }
-
-    /**
-     * Returns {@code true} if mail session is still connected.
-     *
-     * @return {@code true} if mail session is still connected.
-     */
-    public boolean isConnected() {
-        return service.isConnected();
-    }
-
-    /**
-     * Returns the {@link Session}.
-     *
-     * @return the {@link Session}.
-     */
-    public Session getSession() {
-        return session;
-    }
-
-    /**
-     * Returns the {@link Service}.
-     *
-     * @return the {@link Service}.
-     */
-    public abstract T getService();
-
-    public static class Defaults {
-        /**
-         * If set to {@code true}, the setFileName method uses the
-         * {@link MimeUtility#encodeText(String)} to encode any non-ASCII characters in the filename.
-         * Note that this encoding violates the MIME specification, but is useful for interoperating
-         * with some mail clients that use this convention. The default is {@code true}.
-         */
-        public static boolean mailMimeEncodefilename = true;
-        /**
-         * If set to {@code true}, the setFileName method uses the
-         * {@link MimeUtility#encodeText(String)} to encode any non-ASCII characters in the filename.
-         * Note that this encoding violates the MIME specification, but is useful for interoperating
-         * with some mail clients that use this convention. The default is {@code true}.
-         */
-        public static boolean mailMimeDecodefilename = true;
-    }
-}

+ 0 - 104
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/Pop3Server.java

@@ -1,104 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.Authenticator;
-import jakarta.mail.NoSuchProviderException;
-import jakarta.mail.Session;
-import jakarta.mail.Store;
-
-import java.io.File;
-import java.util.Properties;
-import java.util.function.Consumer;
-
-import static jodd.util.StringPool.TRUE;
-
-/**
- * Represents simple plain POP server for sending emails.
- */
-public class Pop3Server extends MailServer<ReceiveMailSession> {
-
-    protected static final String PROTOCOL_POP3 = "pop3";
-
-    /**
-     * Default POP3 port.
-     */
-    protected static final int DEFAULT_POP3_PORT = 110;
-
-    public Pop3Server(final Builder builder) {
-        super(builder, DEFAULT_POP3_PORT);
-    }
-
-    protected Pop3Server(final Builder builder, final int defaultPort) {
-        super(builder, defaultPort);
-    }
-
-    @Override
-    protected Properties createSessionProperties() {
-        final Properties props = super.createSessionProperties();
-
-        props.setProperty(MAIL_POP3_HOST, host);
-        props.setProperty(MAIL_POP3_PORT, String.valueOf(port));
-
-        if (authenticator != null) {
-            props.setProperty(MAIL_POP3_AUTH, TRUE);
-        }
-
-        if (timeout > 0) {
-            final String timeoutValue = String.valueOf(timeout);
-            props.put(MAIL_POP3_CONNECTIONTIMEOUT, timeoutValue);
-            props.put(MAIL_POP3_TIMEOUT, timeoutValue);
-        }
-
-        return props;
-    }
-
-    /**
-     * Returns email store.
-     *
-     * @return POP3Store
-     * @throws NoSuchProviderException If a provider for the given protocol is not found.
-     */
-    protected Store getStore(final Session session) throws NoSuchProviderException {
-        return session.getStore(PROTOCOL_POP3);
-    }
-
-    /**
-     * {@inheritDoc}
-     *
-     * @return {@link ReceiveMailSession}
-     * @see EmailUtil#createSession(String, Properties, Authenticator, File, Consumer)
-     */
-    @Override
-    public ReceiveMailSession createSession() {
-        return EmailUtil.createSession(
-                PROTOCOL_POP3,
-                createSessionProperties(),
-                authenticator,
-                attachmentStorage, debugConsumer);
-    }
-
-}

+ 0 - 87
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/Pop3SslServer.java

@@ -1,87 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.PasswordAuthentication;
-import jakarta.mail.Session;
-import jakarta.mail.URLName;
-import jodd.util.StringPool;
-import org.eclipse.angus.mail.pop3.POP3SSLStore;
-
-import java.util.Properties;
-
-/**
- * POP3 SSL server.
- */
-public class Pop3SslServer extends Pop3Server {
-
-    protected static final int DEFAULT_SSL_PORT = 995;
-
-    public Pop3SslServer(final Builder builder) {
-        super(builder, DEFAULT_SSL_PORT);
-    }
-
-    @Override
-    protected Properties createSessionProperties() {
-        final Properties props = super.createSessionProperties();
-
-        props.setProperty(MAIL_POP3_SOCKET_FACTORY_PORT, String.valueOf(port));
-        props.setProperty(MAIL_POP3_SOCKET_FACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
-        props.setProperty(MAIL_POP3_SOCKET_FACTORY_FALLBACK, StringPool.FALSE);
-
-        return props;
-    }
-
-    /**
-     * Returns email store.
-     *
-     * @param session {@link Session}
-     * @return POP3SSLStore
-     */
-    @Override
-    protected POP3SSLStore getStore(final Session session) {
-        final SimpleAuthenticator simpleAuthenticator = (SimpleAuthenticator) authenticator;
-        final URLName url;
-
-        if (simpleAuthenticator == null) {
-            url = new URLName(
-                    PROTOCOL_POP3,
-                    host, port,
-                    StringPool.EMPTY,
-                    null, null);
-        } else {
-            final PasswordAuthentication pa = simpleAuthenticator.getPasswordAuthentication();
-            url = new URLName(
-                    PROTOCOL_POP3,
-                    host, port,
-                    StringPool.EMPTY,
-                    pa.getUserName(), pa.getPassword());
-        }
-
-        return new POP3SSLStore(session, url);
-    }
-
-}

+ 0 - 730
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/RFC2822AddressParser.java

@@ -1,730 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.internet.InternetAddress;
-import jodd.util.StringPool;
-
-import java.io.UnsupportedEncodingException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Utility class to parse, clean up, and extract email addresses per RFC2822 syntax.
- * It can be trusted to only provide authenticated results.
- * This class has been successfully used on many billion real-world addresses, live in
- * production environments, but it's not perfect yet, since the standard is quite complex.
- * <p>
- * Note: Unlike <code>InternetAddress</code>, this class will preserve any RFC-2047-encoding of international
- * characters.
- */
-public class RFC2822AddressParser {
-    /**
-     * Strict parser.
-     */
-    public static final RFC2822AddressParser STRICT =
-            new RFC2822AddressParser()
-                    .allowDomainLiterals(true)
-                    .allowQuotedIdentifiers(true)
-                    .allowDotInAtext(false)
-                    .extractCfwsPersonalName(true)
-                    .allowSquareBracketsInAtext(false)
-                    .allowParentheseInLocalpart(true);
-    /**
-     * Loose parser.
-     */
-    public static final RFC2822AddressParser LOOSE = new RFC2822AddressParser();
-    private static final Pattern ESCAPED_QUOTE_PATTERN = Pattern.compile("\\\\\"");
-    private static final Pattern ESCAPED_BSLASH_PATTERN = Pattern.compile("\\\\\\\\");
-    private boolean ALLOW_DOMAIN_LITERALS = false;
-    private boolean ALLOW_QUOTED_IDENTIFIERS = true;
-    private boolean ALLOW_DOT_IN_ATEXT = false;
-    private boolean EXTRACT_CFWS_PERSONAL_NAMES = true;
-    private boolean ALLOW_SQUARE_BRACKETS_IN_ATEXT = false;
-    private boolean ALLOW_PARENS_IN_LOCALPART = true;
-    private Pattern _MAILBOX_PATTERN;
-    private Pattern _RETURN_PATH_PATTERN;
-    private Pattern _ADDR_SPEC_PATTERN;        // internal
-    private Pattern _COMMENT_PATTERN;        // internal
-
-    // ---------------------------------------------------------------- parse
-    private Pattern _QUOTED_STRING_WO_CFWS_PATTERN;  // internal
-
-    /**
-     * If the string starts and ends with start and end char, remove them,
-     * otherwise return the string as it was passed in.
-     */
-    private static String removeAnyBounding(final char s, final char e, final String str) {
-        if (str == null || str.length() < 2) {
-            return str;
-        }
-
-        if (str.startsWith(String.valueOf(s)) && str.endsWith(String.valueOf(e))) {
-            return str.substring(1, str.length() - 1);
-        }
-
-        return str;
-    }
-
-    /**
-     * Changes the behavior of the domain parsing. If {@code true}, the parser will
-     * allow 2822 domains, which include single-level domains (e.g. bob@localhost) as well
-     * as domain literals, e.g.:
-     * <p>
-     * <ul>
-     * <li><code>someone@[192.168.1.100]</code> or</li>
-     * <li><code>john.doe@[23:33:A2:22:16:1F]</code> or</li>
-     * <li><code>me@[my computer]</code></li>
-     * </ul>
-     * <p>
-     * The RFC says these are valid email addresses, but many don't like
-     * allowing them. If you don't want to allow them, and only want to allow valid domain names
-     * (<a href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a>, x.y.z.com, etc),
-     * and specifically only those with at least two levels ("example.com"), then
-     * set this flag to {@code false}.
-     */
-    public RFC2822AddressParser allowDomainLiterals(final boolean allow) {
-        ALLOW_DOMAIN_LITERALS = allow;
-        resetPatterns();
-        return this;
-    }
-
-    /**
-     * Defines if quoted identifiers are allowed.
-     * Using quotes and angle brackets around the raw address may be allowed, e.g.:
-     * <p>
-     * <ul>
-     * <li><code>"John Smith" &lt;john.smith@somewhere.com&gt;</code></li>
-     * </ul>
-     * <p>
-     * The RFC says this is a valid mailbox. If you don't want to
-     * allow this, because for example, you only want users to enter in
-     * a raw address (<code>john.smith@somewhere.com</code> - no quotes or angle
-     * brackets), then set the flag {@code false}.
-     */
-    public RFC2822AddressParser allowQuotedIdentifiers(final boolean allow) {
-        ALLOW_QUOTED_IDENTIFIERS = allow;
-        resetPatterns();
-        return this;
-    }
-
-    // ---------------------------------------------------------------- regexp
-
-    /**
-     * Allows &quot;.&quot; to appear in atext (note: only atext which appears
-     * in the 2822 &quot;name-addr&quot; part of the address, not the other instances).
-     * <p>
-     * The addresses:
-     * <ul>
-     * <li><code>Kayaks.org &lt;kayaks@kayaks.org&gt;</code></li>
-     * <li><code>Bob K. Smith&lt;bobksmith@bob.net&gt;</code></li>
-     * </ul>
-     * ...are not valid. They should be:
-     * <ul>
-     * <li><code>&quot;Kayaks.org&quot; &lt;kayaks@kayaks.org&gt;</code></li>
-     * <li><code>&quot;Bob K. Smith&quot; &lt;bobksmith@bob.net&gt;</code></li>
-     * </ul>
-     * If this boolean is set to false, the parser will act per 2822 and will require
-     * the quotes; if set to true, it will allow the use of &quot;.&quot; without quotes.
-     */
-    public RFC2822AddressParser allowDotInAtext(final boolean allow) {
-        ALLOW_DOT_IN_ATEXT = allow;
-        resetPatterns();
-        return this;
-    }
-
-    /**
-     * Controls the behavior of getInternetAddress. If true, allows the real world practice of:
-     * <ul>
-     * <li>&lt;bob@example.com&gt; (Bob Smith)</li>
-     * </ul>
-     * <p>
-     * In this case, &quot;Bob Smith&quot; is not technically the personal name, just a
-     * comment. If this is set to true, the methods will convert this into:
-     * <ul>
-     * <li>Bob Smith &lt;bob@example.com&gt;</li>
-     * </ul>
-     * <p>
-     * This also happens somewhat more often and appropriately with
-     * <code>mailer-daemon@blah.com (Mail Delivery System)</code>.
-     * <p>
-     * <p>
-     * If a personal name appears to the left and CFWS appears to the right of an address,
-     * the methods will favor the personal name to the left. If the methods need to use the
-     * CFWS following the address, they will take the first comment token they find.
-     */
-    public RFC2822AddressParser extractCfwsPersonalName(final boolean extract) {
-        EXTRACT_CFWS_PERSONAL_NAMES = extract;
-        resetPatterns();
-        return this;
-    }
-
-    /**
-     * Allows &quot;[&quot; or &quot;]&quot; to appear in atext.
-     * The address:
-     * <ul><li><code>[Kayaks] &lt;kayaks@kayaks.org&gt;</code></li></ul>
-     * <p>
-     * ...is not valid. It should be:
-     * <p>
-     * <ul><li><code>&quot;[Kayaks]&quot; &lt;kayaks@kayaks.org&gt;</code></li></ul>
-     * <p>
-     * If this boolean is set to false, the parser will act per 2822 and will require
-     * the quotes; if set to true, it will allow them to be missing.
-     * <p>
-     * Use at your own risk. There may be some issue with enabling this feature in conjunction
-     * with {@link #allowDomainLiterals(boolean)}.
-     */
-    public RFC2822AddressParser allowSquareBracketsInAtext(final boolean allow) {
-        ALLOW_SQUARE_BRACKETS_IN_ATEXT = allow;
-        resetPatterns();
-        return this;
-    }
-
-    /**
-     * Allows &quot;)&quot; or &quot;(&quot; to appear in quoted versions of
-     * the localpart (they are never allowed in unquoted versions).
-     * The default (2822) behavior is to allow this, i.e. boolean true.
-     * You can disallow it, but better to leave it true.
-     */
-    public RFC2822AddressParser allowParentheseInLocalpart(final boolean allow) {
-        ALLOW_PARENS_IN_LOCALPART = allow;
-        resetPatterns();
-        return this;
-    }
-
-    /**
-     * Parses email address. Returns {@link ParsedAddress parsed address}, that might be valid or not.
-     */
-    public ParsedAddress parse(String email) {
-        email = email.trim();
-
-        // match all
-
-        final Matcher mailboxMatcher = MAILBOX_PATTERN().matcher(email);
-        final boolean mailboxMatcherMatches = mailboxMatcher.matches();
-        final String[] mailboxMatcherParts = mailboxMatcherMatches ? _calcMatcherParts(mailboxMatcher) : null;
-
-        final Matcher returnPathMatcher = RETURN_PATH_PATTERN().matcher(email);
-        final boolean returnPathMatches = returnPathMatcher.matches();
-
-        // extract
-
-        String personalName = null;
-        String localPart = null;
-        String domain = null;
-        InternetAddress internetAddress = null;
-        String returnPathAddress = null;
-
-        if (mailboxMatcherMatches) {
-            personalName = mailboxMatcherParts[0];
-            localPart = mailboxMatcherParts[1];
-            domain = mailboxMatcherParts[2];
-            internetAddress = pullFromGroups(mailboxMatcher);
-        }
-
-        if (returnPathMatches) {
-            if (internetAddress != null) {
-                returnPathAddress = internetAddress.getAddress();
-            } else {
-                returnPathAddress = StringPool.EMPTY;
-            }
-        }
-
-        return new ParsedAddress(mailboxMatcherMatches, personalName, localPart, domain, internetAddress, returnPathMatches, returnPathAddress);
-    }
-
-    /**
-     * Convenient shortcut of {@link #parse(String)} that returns {@code InternetAddress} or {@code null}.
-     */
-    public InternetAddress parseToInternetAddress(final String email) {
-        final ParsedAddress parsedAddress = parse(email);
-
-        if (!parsedAddress.isValid()) {
-            return null;
-        }
-
-        return parsedAddress.getInternetAddress();
-    }
-
-    /**
-     * Convenient shortcut of {@link #parse(String)} that returns {@link EmailAddress} or {@code null}.
-     */
-    public EmailAddress parseToEmailAddress(final String email) {
-        final ParsedAddress parsedAddress = parse(email);
-
-        if (!parsedAddress.isValid()) {
-            return null;
-        }
-
-        return new EmailAddress(parsedAddress.getPersonalName(), parsedAddress.getLocalPart() + '@' + parsedAddress.getDomain());
-    }
-
-    private Pattern MAILBOX_PATTERN() {
-        if (_MAILBOX_PATTERN == null) {
-            buildPatterns();
-        }
-        return _MAILBOX_PATTERN;
-    }
-
-    private Pattern RETURN_PATH_PATTERN() {
-        if (_RETURN_PATH_PATTERN == null) {
-            buildPatterns();
-        }
-        return _RETURN_PATH_PATTERN;
-    }
-
-    /**
-     * Resets patterns so they can be build on next use.
-     */
-    private void resetPatterns() {
-        _MAILBOX_PATTERN = null;
-        _RETURN_PATH_PATTERN = null;
-    }
-
-    /**
-     * Builds all regexp patterns.
-     */
-    private void buildPatterns() {
-
-        // http://tools.ietf.org/html/rfc2822
-
-        // RFC 2822 2.2.2 Structured Header Field Bodies
-
-        final String CRLF = "\\r\\n";
-        final String WSP = "[ \\t]";
-        final String FWSP = "(?:" + WSP + "*" + CRLF + ")?" + WSP + "+";
-
-        // RFC 2822 3.2.1 Primitive tokens
-
-        final String D_QUOTE = "\\\"";
-        final String NO_WS_CTL = "\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F";
-        final String ASCII_TEXT = "[\\x01-\\x09\\x0B\\x0C\\x0E-\\x7F]";
-
-        // RFC 2822 3.2.2 Quoted characters
-
-        final String QUOTED_PAIR = "(?:\\\\" + ASCII_TEXT + ")";
-
-        // RFC 2822 3.2.3 CFWS specification
-
-        final String C_TEXT = "[" + NO_WS_CTL + "\\!-\\'\\*-\\[\\]-\\~]";
-        final String C_CONTENT = C_TEXT + "|" + QUOTED_PAIR; // + "|" + comment;
-        final String COMMENT = "\\((?:(?:" + FWSP + ")?" + C_CONTENT + ")*(?:" + FWSP + ")?\\)";
-        final String CFWS = "(?:(?:" + FWSP + ")?" + COMMENT + ")*(?:(?:(?:" + FWSP + ")?" + COMMENT + ")|(?:" + FWSP + "))";
-
-        // RFC 2822 3.2.4 Atom
-
-        final String A_TEXT =
-                "[a-zA-Z0-9\\!\\#-\\'\\*\\+\\-\\/\\=\\?\\^-\\`\\{-\\~"
-                        + (ALLOW_DOT_IN_ATEXT ? "\\." : "")
-                        + (ALLOW_SQUARE_BRACKETS_IN_ATEXT ? "\\[\\]" : "") + "]";
-        final String REGULAR_A_TEXT = "[a-zA-Z0-9\\!\\#-\\'\\*\\+\\-\\/\\=\\?\\^-\\`\\{-\\~]";
-
-        final String ATOM = "(?:" + CFWS + ")?" + A_TEXT + "+" + "(?:" + CFWS + ")?";
-        final String DOT_ATOM_TEXT = REGULAR_A_TEXT + "+" + "(?:" + "\\." + REGULAR_A_TEXT + "+)*";
-        final String CAP_DOT_ATOM_NO_CFWS = "(?:" + CFWS + ")?(" + DOT_ATOM_TEXT + ")(?:" + CFWS + ")?";
-        final String CAP_DOT_ATOM_TRAILING_CFWS = "(?:" + CFWS + ")?(" + DOT_ATOM_TEXT + ")(" + CFWS + ")?";
-
-        // RFC 2822 3.2.5 Quoted strings
-
-        final String Q_TEXT = "[" + NO_WS_CTL + "\\!\\#-\\[\\]-\\~]";
-        final String LOCAL_PART_Q_TEXT = "[" + NO_WS_CTL + (ALLOW_PARENS_IN_LOCALPART ? "\\!\\#-\\[\\]-\\~]" : "\\!\\#-\\'\\*-\\[\\]-\\~]");
-
-        final String Q_CONTENT = "(?:" + Q_TEXT + "|" + QUOTED_PAIR + ")";
-        final String LOCAL_PART_Q_CONTENT = "(?>" + LOCAL_PART_Q_TEXT + "|" + QUOTED_PAIR + ")";
-        final String QUOTED_STRING_WOCFWS = D_QUOTE + "(?>(?:" + FWSP + ")?" + Q_CONTENT + ")*(?:" + FWSP + ")?" + D_QUOTE;
-        final String QUOTED_STRING = "(?:" + CFWS + ")?" + QUOTED_STRING_WOCFWS + "(?:" + CFWS + ")?";
-        final String LOCAL_PART_QUOTED_STRING = "(?:" + CFWS + ")?(" + D_QUOTE + "(?:(?:" + FWSP + ")?" + LOCAL_PART_Q_CONTENT + ")*(?:" + FWSP + ")?" + D_QUOTE + ")(?:" + CFWS + ")?";
-
-        // RFC 2822 3.2.6 Miscellaneous tokens
-
-        final String WORD = "(?:(?:" + ATOM + ")|(?:" + QUOTED_STRING + "))";
-
-        // by 2822: phrase = 1*word / obs-phrase
-        // implemented here as: phrase = word (FWS word)*
-        // so that aaaa can't be four words, which can cause tons of recursive backtracking
-
-        final String PHRASE = WORD + "(?:(?:" + FWSP + ")" + WORD + ")*";
-
-        // RFC 1035 tokens for domain names
-
-        final String LETTER = "[a-zA-Z]";
-        final String LET_DIG = "[a-zA-Z0-9]";
-        final String LET_DIG_HYP = "[a-zA-Z0-9-]";
-        final String RFC_LABEL = LET_DIG + "(?:" + LET_DIG_HYP + "{0,61}" + LET_DIG + ")?";
-        final String RFC_1035_DOMAIN_NAME = RFC_LABEL + "(?:\\." + RFC_LABEL + ")*\\." + LETTER + "{2,6}";
-
-        // RFC 2822 3.4 Address specification
-
-        final String D_TEXT = "[" + NO_WS_CTL + "\\!-Z\\^-\\~]";
-
-        final String D_CONTENT = D_TEXT + "|" + QUOTED_PAIR;
-        final String CAP_DOMAIN_LITERAL_NO_CFWS = "(?:" + CFWS + ")?" + "(\\[" + "(?:(?:" + FWSP + ")?(?:" + D_CONTENT + ")+)*(?:" + FWSP + ")?\\])" + "(?:" + CFWS + ")?";
-        final String CAP_DOMAIN_LITERAL_TRAILING_CFWS = "(?:" + CFWS + ")?" + "(\\[" + "(?:(?:" + FWSP + ")?(?:" + D_CONTENT + ")+)*(?:" + FWSP + ")?\\])" + "(" + CFWS + ")?";
-        final String RFC_2822_DOMAIN = "(?:" + CAP_DOT_ATOM_NO_CFWS + "|" + CAP_DOMAIN_LITERAL_NO_CFWS + ")";
-        final String CAP_CFWSR_FC2822_DOMAIN = "(?:" + CAP_DOT_ATOM_TRAILING_CFWS + "|" + CAP_DOMAIN_LITERAL_TRAILING_CFWS + ")";
-
-        final String DOMAIN = ALLOW_DOMAIN_LITERALS ? RFC_2822_DOMAIN : "(?:" + CFWS + ")?(" + RFC_1035_DOMAIN_NAME + ")(?:" + CFWS + ")?";
-        final String CAP_CFWS_DOMAIN = ALLOW_DOMAIN_LITERALS ? CAP_CFWSR_FC2822_DOMAIN : "(?:" + CFWS + ")?(" + RFC_1035_DOMAIN_NAME + ")(" + CFWS + ")?";
-        final String LOCAL_PART = "(" + CAP_DOT_ATOM_NO_CFWS + "|" + LOCAL_PART_QUOTED_STRING + ")";
-
-        // uniqueAddrSpec exists so we can have a duplicate tree that has a capturing group
-        // instead of a non-capturing group for the trailing CFWS after the domain token
-        // that we wouldn't want if it was inside
-        // an angleAddr. The matching should be otherwise identical.
-
-        final String ADDR_SPEC = LOCAL_PART + "@" + DOMAIN;
-        final String UNIQUE_ADDR_SPEC = LOCAL_PART + "@" + CAP_CFWS_DOMAIN;
-        final String ANGLE_ADDR = "(?:" + CFWS + ")?<" + ADDR_SPEC + ">(" + CFWS + ")?";
-
-        final String NAME_ADDR = "(" + PHRASE + ")??(" + ANGLE_ADDR + ")";
-        final String MAIL_BOX = (ALLOW_QUOTED_IDENTIFIERS ? "(" + NAME_ADDR + ")|" : "") + "(" + UNIQUE_ADDR_SPEC + ")";
-
-        final String RETURN_PATH = "(?:(?:" + CFWS + ")?<((?:" + CFWS + ")?|" + ADDR_SPEC + ")>(?:" + CFWS + ")?)";
-
-        // private static final String mailboxList = "(?:(?:" + mailbox + ")(?:,(?:" + mailbox + "))*)";
-        // private static final String groupPostfix = "(?:" + CFWS + "|(?:" + mailboxList + ")" + ")?;(?:" + CFWS + ")?";
-        // private static final String groupPrefix = phrase + ":";
-        // private static final String group = groupPrefix + groupPostfix;
-        // private static final String address = "(?:(?:" + mailbox + ")|(?:" + group + "))"
-
-
-        // Java regex pattern for 2822
-        _MAILBOX_PATTERN = Pattern.compile(MAIL_BOX);
-
-        _ADDR_SPEC_PATTERN = Pattern.compile(ADDR_SPEC);
-        // final Pattern MAILBOX_LIST_PATTERN = Pattern.compile(mailboxList);
-        _COMMENT_PATTERN = Pattern.compile(COMMENT);
-
-        _QUOTED_STRING_WO_CFWS_PATTERN = Pattern.compile(QUOTED_STRING_WOCFWS);
-        _RETURN_PATH_PATTERN = Pattern.compile(RETURN_PATH);
-    }
-
-
-    // ---------------------------------------------------------------- utilities
-
-    private InternetAddress pullFromGroups(final Matcher m) {
-        InternetAddress currentInternetAddress;
-        final String[] parts = _calcMatcherParts(m);
-
-        if (parts[1] == null || parts[2] == null) {
-            return null;
-        }
-
-        // if for some reason you want to require that the result be re-parsable by
-        // InternetAddress, you
-        // could uncomment the appropriate stuff below, but note that not all the utility
-        // functions use pullFromGroups; some call getMatcherParts directly.
-        try {
-            // currentInternetAddress = new InternetAddress(parts[0] + " <" + parts[1] + "@" +
-            //                                 parts[2]+ ">", true);
-            // so it parses it OK, but since javamail doesn't extract too well
-            // we make sure that the consistent parts
-            // are correct
-
-            currentInternetAddress = new InternetAddress();
-            currentInternetAddress.setPersonal(parts[0]);
-            currentInternetAddress.setAddress(parts[1] + "@" + parts[2]);
-        } catch (final UnsupportedEncodingException uee) {
-            currentInternetAddress = null;
-        }
-
-        return currentInternetAddress;
-    }
-
-    private String[] _calcMatcherParts(final Matcher m) {
-        String currentLocalpart = null;
-        String currentDomainpart = null;
-        final String localPartDa;
-        String localPartQs = null;
-        final String domainPartDa;
-        String domainPartDl = null;
-        String personalString = null;
-
-        // see the group-ID lists in the grammar comments
-
-        if (ALLOW_QUOTED_IDENTIFIERS) {
-            if (ALLOW_DOMAIN_LITERALS) {
-                // yes quoted identifiers, yes domain literals
-
-                if (m.group(1) != null) {
-                    // name-addr form
-                    localPartDa = m.group(5);
-                    if (localPartDa == null) {
-                        localPartQs = m.group(6);
-                    }
-
-                    domainPartDa = m.group(7);
-                    if (domainPartDa == null) {
-                        domainPartDl = m.group(8);
-                    }
-
-                    currentLocalpart = (localPartDa == null ? localPartQs : localPartDa);
-
-                    currentDomainpart = (domainPartDa == null ? domainPartDl : domainPartDa);
-
-                    personalString = m.group(2);
-                    if (personalString == null && EXTRACT_CFWS_PERSONAL_NAMES) {
-                        personalString = m.group(9);
-                        personalString = removeAnyBounding('(', ')', getFirstComment(personalString));
-                    }
-                } else if (m.group(10) != null) {
-                    // addr-spec form
-
-                    localPartDa = m.group(12);
-                    if (localPartDa == null) {
-                        localPartQs = m.group(13);
-                    }
-
-                    domainPartDa = m.group(14);
-                    if (domainPartDa == null) {
-                        domainPartDl = m.group(15);
-                    }
-
-                    currentLocalpart = (localPartDa == null ? localPartQs : localPartDa);
-
-                    currentDomainpart = (domainPartDa == null ? domainPartDl : domainPartDa);
-
-                    if (EXTRACT_CFWS_PERSONAL_NAMES) {
-                        personalString = m.group(16);
-                        personalString = removeAnyBounding('(', ')', getFirstComment(personalString));
-                    }
-                }
-            } else {
-                // yes quoted identifiers, no domain literals
-
-                if (m.group(1) != null) {
-                    // name-addr form
-
-                    localPartDa = m.group(5);
-                    if (localPartDa == null) {
-                        localPartQs = m.group(6);
-                    }
-
-                    currentLocalpart = (localPartDa == null ? localPartQs : localPartDa);
-
-                    currentDomainpart = m.group(7);
-
-                    personalString = m.group(2);
-                    if (personalString == null && EXTRACT_CFWS_PERSONAL_NAMES) {
-                        personalString = m.group(8);
-                        personalString = removeAnyBounding('(', ')', getFirstComment(personalString));
-                    }
-                } else if (m.group(9) != null) {
-                    // addr-spec form
-
-                    localPartDa = m.group(11);
-                    if (localPartDa == null) {
-                        localPartQs = m.group(12);
-                    }
-
-                    currentLocalpart = (localPartDa == null ? localPartQs : localPartDa);
-
-                    currentDomainpart = m.group(13);
-
-                    if (EXTRACT_CFWS_PERSONAL_NAMES) {
-                        personalString = m.group(14);
-                        personalString = removeAnyBounding('(', ')', getFirstComment(personalString));
-                    }
-                }
-            }
-        } else {
-            // no quoted identifiers, yes|no domain literals
-
-            localPartDa = m.group(3);
-            if (localPartDa == null) {
-                localPartQs = m.group(4);
-            }
-
-            domainPartDa = m.group(5);
-            if (domainPartDa == null && ALLOW_DOMAIN_LITERALS) {
-                domainPartDl = m.group(6);
-            }
-
-            currentLocalpart = (localPartDa == null ? localPartQs : localPartDa);
-
-            currentDomainpart = (domainPartDa == null ? domainPartDl : domainPartDa);
-
-            if (EXTRACT_CFWS_PERSONAL_NAMES) {
-                personalString = m.group((ALLOW_DOMAIN_LITERALS ? 1 : 0) + 6);
-                personalString = removeAnyBounding('(', ')', getFirstComment(personalString));
-            }
-        }
-
-        if (currentLocalpart != null) {
-            currentLocalpart = currentLocalpart.trim();
-        }
-        if (currentDomainpart != null) {
-            currentDomainpart = currentDomainpart.trim();
-        }
-        if (personalString != null) {
-            // trim even though calling cPS which trims, because the latter may return
-            // the same thing back without trimming
-            personalString = personalString.trim();
-            personalString = cleanupPersonalString(personalString);
-        }
-
-        // remove any unnecessary bounding quotes from the localpart:
-
-        final String testAddr = removeAnyBounding('"', '"', currentLocalpart) + "@" + currentDomainpart;
-
-        if (_ADDR_SPEC_PATTERN.matcher(testAddr).matches()) {
-            currentLocalpart = removeAnyBounding('"', '"', currentLocalpart);
-        }
-
-        return (new String[]{personalString, currentLocalpart, currentDomainpart});
-    }
-
-    /**
-     * Given a string, extract the first matched comment token as defined in 2822, trimmed;
-     * return null on all errors or non-findings.
-     * <p>
-     * Note for future improvement: if COMMENT_PATTERN could handle nested
-     * comments, then this should be able to as well, but if this method were to be used to
-     * find the CFWS personal name (see boolean option) then such a nested comment would
-     * probably not be the one you were looking for?
-     */
-    private String getFirstComment(final String text) {
-        if (text == null) {
-            return null; // important
-        }
-
-        final Matcher m = _COMMENT_PATTERN.matcher(text);
-
-        if (!m.find()) {
-            return null;
-        }
-
-        return m.group().trim();    // must trim
-    }
-
-    private String cleanupPersonalString(String text) {
-        if (text == null) {
-            return null;
-        }
-        text = text.trim();
-
-        final Matcher m = _QUOTED_STRING_WO_CFWS_PATTERN.matcher(text);
-
-        if (!m.matches()) {
-            return text;
-        }
-
-        text = removeAnyBounding('"', '"', m.group());
-
-        text = ESCAPED_BSLASH_PATTERN.matcher(text).replaceAll("\\\\");
-        text = ESCAPED_QUOTE_PATTERN.matcher(text).replaceAll("\"");
-
-        return text.trim();
-    }
-
-    /**
-     * Parsed message address and various information.
-     */
-    public static class ParsedAddress {
-        private final boolean isValid;
-        private final String personalName;
-        private final String localPart;
-        private final String domain;
-        private final InternetAddress internetAddress;
-        private final boolean validReturnPath;
-        private final String returnPathAddress;
-
-        private ParsedAddress(
-                final boolean isValid,
-                final String personalName,
-                final String localPart,
-                final String domain,
-                final InternetAddress internetAddress,
-                final boolean validReturnPath,
-                final String returnPathAddress) {
-
-            this.isValid = isValid;
-            this.personalName = personalName;
-            this.internetAddress = internetAddress;
-            this.domain = domain;
-            this.localPart = localPart;
-            this.validReturnPath = validReturnPath;
-            this.returnPathAddress = returnPathAddress;
-        }
-
-        /**
-         * Returns {@code true} if email is valid.
-         */
-        public boolean isValid() {
-            return isValid;
-        }
-
-        /**
-         * Returns personal name. Returned string does
-         * not reflect any decoding of RFC-2047 encoded personal names.
-         */
-        public String getPersonalName() {
-            return personalName;
-        }
-
-        /**
-         * Returns local part of the email address.
-         */
-        public String getLocalPart() {
-            return localPart;
-        }
-
-        /**
-         * Returns domain part of the email address.
-         */
-        public String getDomain() {
-            return domain;
-        }
-
-        /**
-         * Given a 2822-valid single address string, returns an InternetAddress object holding
-         * that address, otherwise returns null. The email address that comes back from the
-         * resulting InternetAddress object's getAddress() call will have comments and unnecessary
-         * quotation marks or whitespace removed.
-         */
-        public InternetAddress getInternetAddress() {
-            return internetAddress;
-        }
-
-        /**
-         * Returns {@code true} if the email represents a valid return path.
-         */
-        public boolean isValidReturnPath() {
-            return validReturnPath;
-        }
-
-        /**
-         * Pulls out the cleaned-up return path address. May return an empty string.
-         * Returns null if there are any syntax issues or other weirdness, otherwise
-         * the valid, trimmed return path email address without CFWS, surrounding angle brackets,
-         * with quotes stripped where possible, etc. (may return an empty string).
-         */
-        public String getReturnPathAddress() {
-            return returnPathAddress;
-        }
-    }
-
-}

+ 0 - 413
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ReceiveMailSession.java

@@ -1,413 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.*;
-
-import java.io.File;
-import java.util.function.Consumer;
-
-/**
- * Encapsulates {@link Email} receiving session. Prepares and receives {@link Email}s.
- * Some methods do not work on POP3 servers.
- */
-public class ReceiveMailSession extends MailSession<Store> {
-
-    /**
-     * Default folder.
-     */
-    protected static final String DEFAULT_FOLDER = "INBOX";
-
-    static {
-        setupSystemMailProperties();
-    }
-
-    private final File attachmentStorage;
-    /**
-     * The current folder.
-     */
-    Folder folder;
-    String folderName;
-
-    /**
-     * Creates new mail session.
-     *
-     * @param session {@link Session}.
-     * @param store   {@link Store}.
-     */
-    public ReceiveMailSession(final Session session, final Store store, final File attachmentStorage) {
-        super(session, store);
-        this.attachmentStorage = attachmentStorage;
-    }
-
-    /**
-     * Closes folder if opened and expunge deleted messages.
-     */
-    protected static void closeFolderIfOpened(final Folder folder) {
-        if (folder != null && folder.isOpen()) {
-            try {
-                folder.close(true);
-            } catch (final MessagingException ignore) {
-            }
-        }
-    }
-
-    // ---------------------------------------------------------------- folders
-
-    @Override
-    public Store getService() {
-        return (Store) service;
-    }
-
-    /**
-     * Returns array of all {@link Folder}s as {@code String}s. You can use these names in
-     * {@link #useFolder(String)} method.
-     *
-     * @return array of all {@link Folder}s as {@code String}s.
-     */
-    public String[] getAllFolders() {
-        final Folder[] folders;
-        try {
-            folders = getService().getDefaultFolder().list("*");
-        } catch (final MessagingException msgexc) {
-            throw new MailException("Failed to connect to folder", msgexc);
-        }
-        final String[] folderNames = new String[folders.length];
-
-        for (int i = 0; i < folders.length; i++) {
-            final Folder folder = folders[i];
-            folderNames[i] = folder.getFullName();
-        }
-        return folderNames;
-    }
-
-    /**
-     * Opens new folder and closes previously opened folder.
-     *
-     * @param folderName Folder to open
-     */
-    public void useFolder(final String folderName) {
-        useFolder(folderName, Folder.READ_WRITE);
-    }
-
-    /**
-     * Opens new folder and closes previously opened folder with a specific mode.
-     *
-     * @param folderName Folder to open
-     * @param mode       Mode to set
-     */
-    public void useFolder(final String folderName, final int mode) {
-        closeFolderIfOpened(folder);
-
-        try {
-            this.folderName = folderName;
-            this.folder = getService().getFolder(folderName);
-            try {
-                folder.open(mode);
-            } catch (final MailException ignore) {
-                folder.open(Folder.READ_ONLY);
-            }
-        } catch (final MessagingException msgexc) {
-            throw new MailException("Failed to connect to folder: " + folderName, msgexc);
-        }
-    }
-
-    // ---------------------------------------------------------------- open
-
-    /**
-     * Just returns a folder, w/o opening.
-     */
-    public Folder getFolder(final String folder) {
-        try {
-            return getService().getFolder(folder);
-        } catch (final MessagingException e) {
-            throw new MailException("Folder not found: " + folder, e);
-        }
-    }
-
-    /**
-     * Opens default folder: DEFAULT_FOLDER.
-     */
-    public void useDefaultFolder() {
-        closeFolderIfOpened(folder);
-        useFolder(DEFAULT_FOLDER);
-    }
-
-    // ---------------------------------------------------------------- message count
-
-    private void useAndOpenFolderIfNotSet() {
-        if (folder == null) {
-            if (folderName != null) {
-                useFolder(folderName);
-            } else {
-                useDefaultFolder();
-            }
-        }
-    }
-
-    /**
-     * Returns number of messages.
-     *
-     * @return The number of messages.
-     */
-    public int getMessageCount() {
-        useAndOpenFolderIfNotSet();
-        try {
-            return folder.getMessageCount();
-        } catch (final MessagingException msgexc) {
-            throw new MailException(msgexc);
-        }
-    }
-
-    /**
-     * Returns the number of new messages.
-     *
-     * @return The number of new message.
-     */
-    public int getNewMessageCount() {
-        useAndOpenFolderIfNotSet();
-        try {
-            return folder.getNewMessageCount();
-        } catch (final MessagingException msgexc) {
-            throw new MailException(msgexc);
-        }
-    }
-
-    /**
-     * Returns the number of unread messages.
-     */
-    public int getUnreadMessageCount() {
-        useAndOpenFolderIfNotSet();
-        try {
-            return folder.getUnreadMessageCount();
-        } catch (final MessagingException msgexc) {
-            throw new MailException(msgexc);
-        }
-    }
-
-    // ---------------------------------------------------------------- receive builder
-
-    /**
-     * Returns the number of deleted messages.
-     *
-     * @return The number of deleted messages.
-     */
-    public int getDeletedMessageCount() {
-        useAndOpenFolderIfNotSet();
-        try {
-            return folder.getDeletedMessageCount();
-        } catch (final MessagingException msgexc) {
-            throw new MailException(msgexc);
-        }
-    }
-
-    // ---------------------------------------------------------------- receive emails
-
-    /**
-     * Defines the process of received email in a fluent way.
-     */
-    public ReceiverBuilder receive() {
-        return new ReceiverBuilder(this);
-    }
-
-    /**
-     * Receives all emails. Messages are not modified. However, servers
-     * may set SEEN flag anyway, so we force messages to remain
-     * unseen.
-     *
-     * @return array of {@link ReceivedEmail}s.
-     */
-    public ReceivedEmail[] receiveEmail() {
-        return receiveMessages(null, null, null, false, null);
-    }
-
-    /**
-     * Receives all emails that matches given {@link EmailFilter}.
-     * Messages are not modified. However, servers may set SEEN flag anyway,
-     * so we force messages to remain unseen.
-     *
-     * @param filter {@link EmailFilter}
-     * @return array of {@link ReceivedEmail}s.
-     */
-    public ReceivedEmail[] receiveEmail(final EmailFilter filter) {
-        return receiveMessages(filter, null, null, false, null);
-    }
-
-    /**
-     * Receives all emails and mark all messages as 'seen' (ie 'read').
-     *
-     * @return array of {@link ReceivedEmail}s.
-     * @see #receiveEmailAndMarkSeen(EmailFilter)
-     */
-    public ReceivedEmail[] receiveEmailAndMarkSeen() {
-        return receiveEmailAndMarkSeen(null);
-    }
-
-    /**
-     * Receives all emails that matches given {@link EmailFilter}
-     * and mark them as 'seen' (ie 'read').
-     *
-     * @param filter {@link EmailFilter}
-     * @return array of {@link ReceivedEmail}s.
-     */
-    public ReceivedEmail[] receiveEmailAndMarkSeen(final EmailFilter filter) {
-        final Flags flagsToSet = new Flags();
-        flagsToSet.add(Flags.Flag.SEEN);
-        return receiveMessages(filter, flagsToSet, null, false, null);
-    }
-
-    /**
-     * Receives all emails and mark all messages as 'seen' and 'deleted'.
-     *
-     * @return array of {@link ReceivedEmail}s.
-     */
-    public ReceivedEmail[] receiveEmailAndDelete() {
-        return receiveEmailAndDelete(null);
-    }
-
-    /**
-     * Receives all emails that matches given {@link EmailFilter} and
-     * mark all messages as 'seen' and 'deleted'.
-     *
-     * @param filter {@link EmailFilter}
-     * @return array of {@link ReceivedEmail}s.
-     */
-    public ReceivedEmail[] receiveEmailAndDelete(final EmailFilter filter) {
-        final Flags flags = new Flags();
-        flags.add(Flags.Flag.SEEN);
-        flags.add(Flags.Flag.DELETED);
-        return receiveMessages(filter, flags, null, false, null);
-    }
-
-    public ReceivedEmail[] receiveEnvelopes() {
-        return receiveEnvelopes(null);
-    }
-
-    public ReceivedEmail[] receiveEnvelopes(final EmailFilter filter) {
-        return receiveMessages(filter, null, null, true, null);
-    }
-
-
-    // ---------------------------------------------------------------- update
-
-    /**
-     * The main email receiving method.
-     */
-    ReceivedEmail[] receiveMessages(
-            final EmailFilter filter,
-            final Flags flagsToSet,
-            final Flags flagsToUnset,
-            final boolean envelope,
-            final Consumer<Message[]> processedMessageConsumer) {
-        useAndOpenFolderIfNotSet();
-
-        final Message[] messages;
-
-        try {
-            if (filter == null) {
-                messages = folder.getMessages();
-            } else {
-                messages = folder.search(filter.getSearchTerm());
-            }
-
-            if (messages.length == 0) {
-                return ReceivedEmail.EMPTY_ARRAY;
-            }
-
-            if (envelope) {
-                final FetchProfile fetchProfile = new FetchProfile();
-
-                fetchProfile.add(FetchProfile.Item.ENVELOPE);
-                fetchProfile.add(FetchProfile.Item.FLAGS);
-
-                folder.fetch(messages, fetchProfile);
-            }
-
-            // process messages
-
-            final ReceivedEmail[] emails = new ReceivedEmail[messages.length];
-
-            for (int i = 0; i < messages.length; i++) {
-                final Message msg = messages[i];
-
-                // we need to parse message BEFORE flags are set!
-                emails[i] = new ReceivedEmail(msg, envelope, attachmentStorage);
-
-                if (!EmailUtil.isEmptyFlags(flagsToSet)) {
-                    emails[i].flags(flagsToSet);
-                    msg.setFlags(flagsToSet, true);
-                }
-
-                if (!EmailUtil.isEmptyFlags(flagsToUnset)) {
-                    emails[i].flags().remove(flagsToUnset);
-                    msg.setFlags(flagsToUnset, false);
-                }
-
-                if (EmailUtil.isEmptyFlags(flagsToSet) && !emails[i].isSeen()) {
-                    msg.setFlag(Flags.Flag.SEEN, false);
-                }
-            }
-
-            if (processedMessageConsumer != null) {
-                processedMessageConsumer.accept(messages);
-            }
-
-            // if messages were marked to be deleted, we need to expunge the folder
-            if (!EmailUtil.isEmptyFlags(flagsToSet)) {
-                if (flagsToSet.contains(Flags.Flag.DELETED)) {
-                    folder.expunge();
-                }
-            }
-
-            return emails;
-        } catch (final MessagingException msgexc) {
-            throw new MailException("Failed to fetch messages", msgexc);
-        }
-    }
-
-    // ---------------------------------------------------------------- close
-
-    /**
-     * Updates the email flags on the server.
-     */
-    public void updateEmailFlags(final ReceivedEmail receivedEmail) {
-        useAndOpenFolderIfNotSet();
-        try {
-            folder.setFlags(new int[]{receivedEmail.messageNumber()}, receivedEmail.flags(), true);
-        } catch (final MessagingException mex) {
-            throw new MailException("Failed to fetch messages", mex);
-        }
-    }
-
-    @Override
-    public void close() {
-        closeFolderIfOpened(folder);
-        folder = null;
-        folderName = null;
-        super.close();
-    }
-
-}

+ 0 - 515
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ReceivedEmail.java

@@ -1,515 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.*;
-import jakarta.mail.internet.MimeMessage;
-import jakarta.mail.internet.MimePart;
-import jakarta.mail.util.ByteArrayDataSource;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import static jakarta.mail.Flags.Flag;
-
-/**
- * Received email.
- */
-public class ReceivedEmail extends CommonEmail<ReceivedEmail> {
-
-    public static final ReceivedEmail[] EMPTY_ARRAY = new ReceivedEmail[0];
-    /**
-     * {@link List} of attached {@link ReceivedEmail}s.
-     */
-    private final List<ReceivedEmail> attachedMessages = new ArrayList<>();
-    private File attachmentStorage;
-    /**
-     * {@link Message} for this {@link ReceivedEmail}.
-     */
-    private Message originalMessage;
-    /**
-     * {@link Flags} for this {@link ReceivedEmail}.
-     */
-    private Flags flags;
-    private int messageNumber;
-    private String messageId;
-    private Date receivedDate;
-
-    /**
-     * Creates an empty {@link ReceivedEmail}.
-     */
-    private ReceivedEmail() {
-    }
-
-    /**
-     * Creates a {@link ReceivedEmail} from a given {@link Message}.
-     *
-     * @param msg      {@link Message}
-     * @param envelope flag if this is an envelope
-     */
-    public ReceivedEmail(final Message msg, final boolean envelope, final File attachmentStorage) {
-        this.attachmentStorage = attachmentStorage;
-        this.originalMessage = msg;
-        try {
-            parseMessage(msg, envelope);
-        } catch (final Exception ex) {
-            throw new MailException("Message parsing failed", ex);
-        }
-    }
-
-    /**
-     * Static constructor for fluent interface.
-     *
-     * @return new {@link ReceivedEmail}.
-     */
-    public static ReceivedEmail create() {
-        return new ReceivedEmail();
-    }
-
-    /**
-     * Returns the Content-ID of this {@link Part}. Returns {@code null} if none present.
-     *
-     * @param part {@link Part} the Part to parse.
-     * @return String containing content ID.
-     * @throws MessagingException if there is a failure.
-     * @see MimePart#getContentID()
-     */
-    protected static String parseContentId(final Part part) throws MessagingException {
-        if (part instanceof MimePart) {
-            final MimePart mp = (MimePart) part;
-            return mp.getContentID();
-        } else {
-            return null;
-        }
-    }
-
-    // ---------------------------------------------------------------- original message
-
-    /**
-     * Returns {@code true} if the {@link Part} is inline.
-     *
-     * @param part {@link Part} to parse.
-     * @return {@code true} if the {@link Part} is inline.
-     * @throws MessagingException if there is a failure.
-     */
-    protected static boolean parseInline(final Part part) throws MessagingException {
-        if (part instanceof MimePart) {
-            final String dispositionId = part.getDisposition();
-            return dispositionId != null && dispositionId.equalsIgnoreCase("inline");
-        }
-        return false;
-    }
-
-    /**
-     * Creates {@link EmailAttachmentBuilder} from {@link Part} and sets Content ID, inline and name.
-     *
-     * @param part {@link Part}.
-     * @return this
-     * @see #attachment(EmailAttachment)
-     */
-    private static EmailAttachmentBuilder addAttachmentInfo(final Part part) throws MessagingException {
-
-        final String fileName = EmailUtil.resolveFileName(part);
-        final String contentId = parseContentId(part);
-        final boolean isInline = parseInline(part);
-
-        return new EmailAttachmentBuilder()
-                .name(fileName)
-                .contentId(contentId)
-                .inline(isInline);
-    }
-
-    @Override
-    public ReceivedEmail clone() {
-        return create()
-                // original message
-                .originalMessage(originalMessage())
-
-                // flags
-                .flags(flags())
-
-                // message number and id
-                .messageNumber(messageNumber())
-                .messageId(messageId())
-
-                // from / reply-to
-                .from(from())
-                .replyTo(replyTo())
-
-                // recipients
-                .to(to())
-                .cc(cc())
-
-                // subject
-                .subject(subject(), subjectEncoding())
-
-                // dates
-                .receivedDate(receivedDate())
-                .sentDate(sentDate())
-
-                // headers - includes priority
-                .headers(headers())
-
-                // content / attachments
-                .message(messages())
-                .storeAttachments(attachments())
-                .attachedMessages(attachedMessages());
-    }
-
-    // ---------------------------------------------------------------- flags
-
-    /**
-     * Parses {@link Message} and extracts all data for the received message.
-     *
-     * @param msg {@link Message} to parse.
-     * @throws IOException        if there is an error with the content
-     * @throws MessagingException if there is an error.
-     */
-    protected void parseMessage(final Message msg, final boolean envelope) throws MessagingException, IOException {
-        // flags
-        flags(msg.getFlags());
-
-        // message number
-        messageNumber(msg.getMessageNumber());
-
-        if (msg instanceof MimeMessage) {
-            messageId(((MimeMessage) msg).getMessageID());
-        }
-
-
-        // single from
-        final Address[] addresses = msg.getFrom();
-
-        if (addresses != null && addresses.length > 0) {
-            from(addresses[0]);
-        }
-
-        // reply-to
-        replyTo(msg.getReplyTo());
-
-        // recipients
-        to(msg.getRecipients(Message.RecipientType.TO));
-        cc(msg.getRecipients(Message.RecipientType.CC));
-        // no BCC because this will always be empty
-
-        // subject
-        subject(msg.getSubject());
-
-        // dates
-        receivedDate(msg.getReceivedDate());
-        sentDate(msg.getSentDate());
-
-        // headers
-        headers(msg.getAllHeaders());
-
-        // content
-        if (!envelope) {
-            processPart(msg);
-        }
-    }
-
-    /**
-     * Process part of the received message. All parts are simply added to the {@link ReceivedEmail},
-     * i.e. hierarchy is not saved.
-     *
-     * @param part {@link Part} of received message
-     * @throws IOException        if there is an error with the content.
-     * @throws MessagingException if there is an error.
-     */
-    protected void processPart(final Part part) throws MessagingException, IOException {
-        final Object content = part.getContent();
-
-        if (content instanceof String) {
-            addStringContent(part, (String) content);
-        } else if (content instanceof Multipart) {
-            processMultipart((Multipart) content);
-        } else if (content instanceof InputStream) {
-            addAttachment(part, (InputStream) content, attachmentStorage);
-        } else if (content instanceof MimeMessage) {
-            final MimeMessage mimeMessage = (MimeMessage) content;
-            attachedMessage(new ReceivedEmail(mimeMessage, false, attachmentStorage));
-        } else {
-            addAttachment(part, part.getInputStream(), attachmentStorage);
-        }
-    }
-
-    /**
-     * Process the {@link Multipart}.
-     *
-     * @param mp {@link Multipart}
-     * @throws MessagingException if there is a failure.
-     * @throws IOException        if there is an issue with the {@link Multipart}.
-     */
-    private void processMultipart(final Multipart mp) throws MessagingException, IOException {
-        final int count = mp.getCount();
-        for (int i = 0; i < count; i++) {
-            final Part innerPart = mp.getBodyPart(i);
-            processPart(innerPart);
-        }
-    }
-
-    /**
-     * Adds String content as either {@link EmailAttachment} or as {@link EmailMessage}.
-     *
-     * @param part    {@link Part}
-     * @param content Content as {@link String}
-     * @throws MessagingException           if there is a failure.
-     * @throws UnsupportedEncodingException if the named charset is not supported.
-     * @see #message(String, String, String)
-     */
-    private void addStringContent(final Part part, final String content) throws MessagingException, UnsupportedEncodingException {
-        final String contentType = part.getContentType();
-        final String encoding = EmailUtil.extractEncoding(contentType, StandardCharsets.US_ASCII.name());
-
-        final String disposition = part.getDisposition();
-
-        if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
-            addAttachment(part, content.getBytes(encoding));
-        } else {
-            final String mimeType = EmailUtil.extractMimeType(contentType);
-            message(content, mimeType, encoding);
-        }
-    }
-
-    /**
-     * @return {@link Message}
-     */
-    public Message originalMessage() {
-        return originalMessage;
-    }
-
-    /**
-     * Sets the original message.
-     *
-     * @param originalMessage {@link Message} to set.
-     */
-    public ReceivedEmail originalMessage(final Message originalMessage) {
-        this.originalMessage = originalMessage;
-        return this;
-    }
-
-    /**
-     * @return {@link Flags}
-     */
-    public Flags flags() {
-        return flags;
-    }
-
-    /**
-     * Sets the flags.
-     *
-     * @param flags {@link Flags} to set.
-     */
-    public ReceivedEmail flags(final Flags flags) {
-        this.flags = flags;
-        return this;
-    }
-
-    /**
-     * Returns {@code true} if message is answered.
-     *
-     * @return {@code true} if message is answered.
-     */
-    public boolean isAnswered() {
-        return flags.contains(Flag.ANSWERED);
-    }
-
-    // ---------------------------------------------------------------- additional properties
-
-    /**
-     * Returns {@code true} if message is deleted.
-     *
-     * @return {@code true} if message is deleted.
-     */
-    public boolean isDeleted() {
-        return flags.contains(Flag.DELETED);
-    }
-
-    /**
-     * Returns {@code true} if message is draft.
-     */
-    public boolean isDraft() {
-        return flags.contains(Flag.DRAFT);
-    }
-
-    /**
-     * Returns {@code true} is message is flagged.
-     *
-     * @return {@code true} is message is flagged.
-     */
-    public boolean isFlagged() {
-        return flags.contains(Flag.FLAGGED);
-    }
-
-    /**
-     * Returns {@code true} if message is recent.
-     *
-     * @return {@code true} if message is recent.
-     */
-    public boolean isRecent() {
-        return flags.contains(Flag.RECENT);
-    }
-
-    /**
-     * Returns {@code true} if message is seen.
-     *
-     * @return {@code true} if message is seen.
-     */
-    public boolean isSeen() {
-        return flags.contains(Flag.SEEN);
-    }
-
-    /**
-     * Returns message number.
-     *
-     * @return message number
-     */
-    public int messageNumber() {
-        return messageNumber;
-    }
-
-    /**
-     * Returns message ID if set by server.
-     */
-    public String messageId() {
-        return messageId;
-    }
-
-    /**
-     * Sets message number.
-     *
-     * @param messageNumber The message number to set.
-     * @return this
-     */
-    public ReceivedEmail messageNumber(final int messageNumber) {
-        this.messageNumber = messageNumber;
-        return this;
-    }
-
-    /**
-     * Sets message ID.
-     */
-    public ReceivedEmail messageId(final String messageId) {
-        this.messageId = messageId;
-        return this;
-    }
-
-    // ---------------------------------------------------------------- attachments
-
-    /**
-     * Sets email's received {@link Date}.
-     *
-     * @param date The received {@link Date} to set.
-     * @return this
-     */
-    public ReceivedEmail receivedDate(final Date date) {
-        receivedDate = date;
-        return this;
-    }
-
-    /**
-     * Returns email's received {@link Date}.
-     *
-     * @return The email's received {@link Date}.
-     */
-    public Date receivedDate() {
-        return receivedDate;
-    }
-
-    /**
-     * Adds received attachment.
-     *
-     * @param part    {@link Part}.
-     * @param content Content as {@link InputStream}.
-     * @return this
-     * @see #attachment(EmailAttachment)
-     */
-    private ReceivedEmail addAttachment(final Part part, final InputStream content, final File attachmentStorage) throws MessagingException, IOException {
-        final EmailAttachmentBuilder builder = addAttachmentInfo(part);
-        builder.content(content, part.getContentType());
-        if (attachmentStorage != null) {
-            String name = messageId + "-" + (this.attachments().size() + 1);
-            return storeAttachment(builder.buildFileDataSource(name, attachmentStorage));
-        }
-        return storeAttachment(builder.buildByteArrayDataSource());
-    }
-
-    // ---------------------------------------------------------------- inner messages
-
-    /**
-     * Adds received attachment.
-     *
-     * @param part    {@link Part}.
-     * @param content Content as byte array.
-     * @return this
-     * @see #attachment(EmailAttachment)
-     */
-    private ReceivedEmail addAttachment(final Part part, final byte[] content) throws MessagingException {
-        final EmailAttachmentBuilder builder = addAttachmentInfo(part);
-        builder.content(content, part.getContentType());
-        final EmailAttachment<ByteArrayDataSource> attachment = builder.buildByteArrayDataSource();
-        attachment.setSize(content.length);
-        return storeAttachment(attachment);
-    }
-
-    /**
-     * Adds attached {@link ReceivedEmail}s.
-     *
-     * @param emails {@link List} of {@link ReceivedEmail}s to attach.
-     */
-    public ReceivedEmail attachedMessages(final List<ReceivedEmail> emails) {
-        attachedMessages.addAll(emails);
-        return this;
-    }
-
-    /**
-     * Adds attached {@link ReceivedEmail}.
-     *
-     * @param email {@link ReceivedEmail} to attach.
-     * @return this
-     */
-    public ReceivedEmail attachedMessage(final ReceivedEmail email) {
-        attachedMessages.add(email);
-        return this;
-    }
-
-    /**
-     * Returns the {@link List} of attached messages.
-     * If no attached message is available, returns an empty {@link List}.
-     *
-     * @return {@link List} of {@link ReceivedEmail}s.
-     */
-    public List<ReceivedEmail> attachedMessages() {
-        return attachedMessages;
-    }
-
-}

+ 0 - 133
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/ReceiverBuilder.java

@@ -1,133 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.Flags;
-import jakarta.mail.MessagingException;
-
-/**
- * Fluent builder
- */
-public class ReceiverBuilder {
-
-    private final ReceiveMailSession session;
-    private final Flags flagsToSet = new Flags();
-    private final Flags flagsToUnset = new Flags();
-    private EmailFilter filter;
-    private boolean envelopeOnly;
-    private String targetFolder;
-    private String fromFolder;
-
-    public ReceiverBuilder(final ReceiveMailSession session) {
-        this.session = session;
-    }
-
-    /**
-     * Define applied filters.
-     */
-    public ReceiverBuilder filter(final EmailFilter emailFilter) {
-        this.filter = emailFilter;
-        return this;
-    }
-
-    /**
-     * Marks messages as seen after receiving them.
-     */
-    public ReceiverBuilder markSeen() {
-        this.flagsToSet.add(Flags.Flag.SEEN);
-        return this;
-    }
-
-    /**
-     * Marks message with given flag.
-     */
-    public ReceiverBuilder mark(final Flags.Flag flagToSet) {
-        this.flagsToSet.add(flagToSet);
-        return this;
-    }
-
-    /**
-     * Unmarks a message with given flag.
-     */
-    public ReceiverBuilder unmark(final Flags.Flag flagToUnset) {
-        this.flagsToUnset.add(flagToUnset);
-        return this;
-    }
-
-    /**
-     * Deletes messages upon receiving.
-     */
-    public ReceiverBuilder markDeleted() {
-        this.flagsToSet.add(Flags.Flag.DELETED);
-        return this;
-    }
-
-    /**
-     * Sets the working folder.
-     * \
-     */
-    public ReceiverBuilder fromFolder(final String fromFolder) {
-        this.fromFolder = fromFolder;
-        return this;
-    }
-
-    /**
-     * Defines target folder where message will be moved.
-     */
-    public ReceiverBuilder moveToFolder(final String targetFolder) {
-        this.markDeleted();
-        this.targetFolder = targetFolder;
-        return this;
-    }
-
-    /**
-     * Receives only envelopes.
-     */
-    public ReceiverBuilder envelopeOnly() {
-        this.envelopeOnly = true;
-        return this;
-    }
-
-    /**
-     * Receives the emails as specified by the builder.
-     */
-    public ReceivedEmail[] get() {
-        if (fromFolder != null) {
-            session.useFolder(fromFolder);
-        }
-
-        return session.receiveMessages(filter, flagsToSet, flagsToUnset, envelopeOnly, messages -> {
-            if (targetFolder != null) {
-                try {
-                    session.folder.copyMessages(messages, session.getFolder(targetFolder));
-                } catch (MessagingException e) {
-                    throw new MailException("Copying messages failed");
-                }
-            }
-        });
-    }
-
-}

+ 0 - 361
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/SendMailSession.java

@@ -1,361 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.activation.DataHandler;
-import jakarta.activation.DataSource;
-import jakarta.mail.MessagingException;
-import jakarta.mail.Part;
-import jakarta.mail.Session;
-import jakarta.mail.Transport;
-import jakarta.mail.internet.InternetAddress;
-import jakarta.mail.internet.MimeBodyPart;
-import jakarta.mail.internet.MimeMessage;
-import jakarta.mail.internet.MimeMultipart;
-import jodd.util.StringPool;
-
-import java.util.*;
-
-import static jakarta.mail.Message.RecipientType;
-
-/**
- * Encapsulates {@link Email} sending session. Prepares and sends {@link #sendMail(Email)} {@link Email}s.
- */
-public class SendMailSession extends MailSession<Transport> {
-
-    private static final String ALTERNATIVE = "alternative";
-    private static final String RELATED = "related";
-    private static final String CHARSET = ";charset=";
-    private static final String INLINE = "inline";
-
-    static {
-        setupSystemMailProperties();
-    }
-
-    /**
-     * Creates new mail session.
-     *
-     * @param session   {@link Session}
-     * @param transport {@link Transport}
-     */
-    public SendMailSession(final Session session, final Transport transport) {
-        super(session, transport);
-    }
-
-    /**
-     * Sets subject in msgToSet from subject in emailWithData.
-     *
-     * @param emailWithData {@link Email} with data
-     * @param msgToSet      {@link MimeMessage} to set data into.
-     * @throws MessagingException if there is a failure
-     */
-    private static void setSubject(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException {
-        if (emailWithData.subjectEncoding() != null) {
-            msgToSet.setSubject(emailWithData.subject(), emailWithData.subjectEncoding());
-        } else {
-            msgToSet.setSubject(emailWithData.subject());
-        }
-    }
-
-    /**
-     * Sets sent date in msgToSet with sent date from emailWithData.
-     *
-     * @param emailWithData {@link Email} with data
-     * @param msgToSet      {@link MimeMessage} to set data into.
-     * @throws MessagingException if there is a failure
-     */
-    private static void setSentDate(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException {
-        Date date = emailWithData.sentDate();
-        if (date == null) {
-            date = new Date();
-        }
-        msgToSet.setSentDate(date);
-    }
-
-    // ---------------------------------------------------------------- adapter
-
-    /**
-     * Sets headers in msgToSet with headers from emailWithData.
-     *
-     * @param emailWithData {@link Email} with data
-     * @param msgToSet      {@link MimeMessage} to set data into.
-     * @throws MessagingException if there is a failure
-     */
-    private static void setHeaders(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException {
-        final Map<String, String> headers = emailWithData.headers();
-        if (headers != null) {
-            for (final Map.Entry<String, String> entry : headers.entrySet()) {
-                msgToSet.setHeader(entry.getKey(), entry.getValue());
-            }
-        }
-    }
-
-    /**
-     * Returns new {@link MimeBodyPart} with content set as msgMultipart.
-     *
-     * @param msgMultipart {@link MimeMultipart} to add to the new {@link MimeBodyPart}.
-     * @return new {@link MimeBodyPart} with content set as msgMultipart.
-     * @throws MessagingException if there is a failure.
-     */
-    private static MimeBodyPart getBaseBodyPart(final MimeMultipart msgMultipart) throws MessagingException {
-        final MimeBodyPart bodyPart = new MimeBodyPart();
-        bodyPart.setContent(msgMultipart);
-        return bodyPart;
-    }
-
-    /**
-     * Sets emailWithData content into msgToSet.
-     *
-     * @param emailWithData {@link EmailMessage} with data.
-     * @param partToSet     {@link Part} to set data into.
-     * @throws MessagingException if there is a failure.
-     */
-    private static void setContent(final EmailMessage emailWithData, final Part partToSet) throws MessagingException {
-        partToSet.setContent(emailWithData.getContent(), emailWithData.getMimeType() + CHARSET + emailWithData.getEncoding());
-    }
-
-    /**
-     * Filters out the {@link List} of embedded {@link EmailAttachment}s for given {@link EmailMessage}.
-     * This will remove the embedded attachments from the {@link List} and return them in a new {@link List}.
-     *
-     * @param attachments  {@link List} of attachments to search for in emailMessage.
-     * @param emailMessage {@link EmailMessage} to see if attachment is embedded into.
-     * @return {@link List} of embedded {@link EmailAttachment}s; otherwise, returns empty {@link List}.
-     */
-    protected static List<EmailAttachment<? extends DataSource>> filterEmbeddedAttachments(final List<EmailAttachment<? extends DataSource>> attachments, final EmailMessage emailMessage) {
-        final List<EmailAttachment<? extends DataSource>> embeddedAttachments = new ArrayList<>();
-
-        if (attachments == null || attachments.isEmpty() || emailMessage == null) {
-            return embeddedAttachments;
-        }
-
-        final Iterator<EmailAttachment<? extends DataSource>> iterator = attachments.iterator();
-
-        while (iterator.hasNext()) {
-            final EmailAttachment<? extends DataSource> emailAttachment = iterator.next();
-
-            if (emailAttachment.isEmbeddedInto(emailMessage)) {
-                embeddedAttachments.add(emailAttachment);
-                iterator.remove();
-            }
-        }
-
-        return embeddedAttachments;
-    }
-
-    @Override
-    public Transport getService() {
-        return (Transport) service;
-    }
-
-    /**
-     * Prepares message and sends it. Returns Message ID of sent email.
-     *
-     * @param email {@link Email} to send.
-     * @return String representing message ID.
-     */
-    public String sendMail(final Email email) {
-        try {
-            final MimeMessage msg = createMessage(email);
-            getService().sendMessage(msg, msg.getAllRecipients());
-            return msg.getMessageID();
-        } catch (final MessagingException msgexc) {
-            throw new MailException("Failed to send email: " + email, msgexc);
-        }
-    }
-
-    /**
-     * Creates new {@link MimeMessage} from an {@link Email}.
-     *
-     * @param email {@link Email} to be created as a {@link MimeMessage}.
-     * @return {@link MimeMessage} created from an {@link Email}.
-     * @throws MessagingException if there is a failure
-     */
-    protected MimeMessage createMessage(final Email email) throws MessagingException {
-        final Email clone = email.clone();
-
-        final MimeMessage newMsg = new MimeMessage(getSession());
-
-        setPeople(clone, newMsg);
-        setSubject(clone, newMsg);
-        setSentDate(clone, newMsg);
-        setHeaders(clone, newMsg);
-        addBodyData(clone, newMsg);
-        return newMsg;
-    }
-
-    /**
-     * Sets FROM, REPLY-TO and recipients.
-     *
-     * @param emailWithData {@link Email} with data
-     * @param msgToSet      {@link MimeMessage} to set data into.
-     * @throws MessagingException if there is a failure
-     */
-    private void setPeople(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException {
-        msgToSet.setFrom(emailWithData.from().toInternetAddress());
-        msgToSet.setReplyTo(EmailAddress.convert(emailWithData.replyTo()));
-        setRecipients(emailWithData, msgToSet);
-    }
-
-    /**
-     * Sets TO, CC and BCC in msgToSet with TO, CC and BCC from emailWithData.
-     *
-     * @param emailWithData {@link Email} with data
-     * @param msgToSet      {@link MimeMessage} to set data into.
-     * @throws MessagingException if there is a failure.
-     */
-    private void setRecipients(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException {
-        // TO
-        final InternetAddress[] to = EmailAddress.convert(emailWithData.to());
-        if (to.length > 0) {
-            msgToSet.setRecipients(RecipientType.TO, to);
-        }
-
-        // CC
-        final InternetAddress[] cc = EmailAddress.convert(emailWithData.cc());
-        if (cc.length > 0) {
-            msgToSet.setRecipients(RecipientType.CC, cc);
-        }
-
-        // BCC
-        final InternetAddress[] bcc = EmailAddress.convert(emailWithData.bcc());
-        if (bcc.length > 0) {
-            msgToSet.setRecipients(RecipientType.BCC, bcc);
-        }
-    }
-
-    /**
-     * Adds message data and attachments.
-     *
-     * @param emailWithData {@link Email} with data
-     * @param msgToSet      {@link MimeMessage} to set data into.
-     * @throws MessagingException if there is a failure.
-     */
-    private void addBodyData(final Email emailWithData, final MimeMessage msgToSet) throws MessagingException {
-        final List<EmailMessage> messages = emailWithData.messages();
-
-        final int totalMessages = messages.size();
-
-        // Need to use new list since filterEmbeddedAttachments(List) removes attachments from the source List
-        final List<EmailAttachment<? extends DataSource>> attachments = new ArrayList<>(emailWithData.attachments());
-
-        if (attachments.isEmpty() && totalMessages == 1) {
-            // special case: no attachments and just one content
-            setContent(messages.get(0), msgToSet);
-
-        } else {
-            final MimeMultipart multipart = new MimeMultipart();
-
-            final MimeMultipart msgMultipart = new MimeMultipart(ALTERNATIVE);
-            multipart.addBodyPart(getBaseBodyPart(msgMultipart));
-            for (final EmailMessage emailMessage : messages) {
-                msgMultipart.addBodyPart(getBodyPart(emailMessage, attachments));
-            }
-
-            addAnyAttachments(attachments, multipart);
-
-            msgToSet.setContent(multipart);
-        }
-    }
-
-    /**
-     * @param emailMessage {@link EmailMessage} with data.
-     * @param attachments  {@link List} of {@link EmailAttachment}s.
-     * @return new {@link MimeBodyPart} with data from emailMessage and attachments.
-     * @throws MessagingException if there is a failure.
-     */
-    private MimeBodyPart getBodyPart(final EmailMessage emailMessage, final List<EmailAttachment<? extends DataSource>> attachments) throws MessagingException {
-
-        final MimeBodyPart bodyPart = new MimeBodyPart();
-
-        // detect embedded attachments
-        final List<EmailAttachment<? extends DataSource>> embeddedAttachments = filterEmbeddedAttachments(attachments, emailMessage);
-
-        if (embeddedAttachments.isEmpty()) {
-            // no embedded attachments, just add message
-            setContent(emailMessage, bodyPart);
-        } else {
-            attachments.removeAll(embeddedAttachments);
-
-            // embedded attachments detected, join them as related
-            final MimeMultipart relatedMultipart = new MimeMultipart(RELATED);
-
-            final MimeBodyPart messageData = new MimeBodyPart();
-
-            setContent(emailMessage, messageData);
-
-            relatedMultipart.addBodyPart(messageData);
-
-            addAnyAttachments(embeddedAttachments, relatedMultipart);
-
-            bodyPart.setContent(relatedMultipart);
-        }
-
-        return bodyPart;
-    }
-
-    /**
-     * Creates attachment body part. Handles regular and inline attachments.
-     *
-     * @param attachment Body part {@link EmailAttachment}.
-     * @return {@link MimeBodyPart} which represents body part attachment.
-     * @throws MessagingException if there is a failure.
-     */
-    protected MimeBodyPart createAttachmentBodyPart(final EmailAttachment<? extends DataSource> attachment) throws MessagingException {
-        final MimeBodyPart part = new MimeBodyPart();
-
-        final String attachmentName = attachment.getEncodedName();
-        if (attachmentName != null) {
-            part.setFileName(attachmentName);
-        }
-
-        part.setDataHandler(new DataHandler(attachment.getDataSource()));
-
-        if (attachment.getContentId() != null) {
-            part.setContentID(StringPool.LEFT_CHEV + attachment.getContentId() + StringPool.RIGHT_CHEV);
-        }
-        if (attachment.isInline()) {
-            part.setDisposition(INLINE);
-        }
-
-        return part;
-    }
-
-    /**
-     * Adds {@link List} of {@link EmailAttachment}s to multipart.
-     *
-     * @param attachments {@link List} of {@link EmailAttachment}s to add to multipart. This can be {@code null}.
-     * @param multipart   {@link MimeMultipart} to set data into.
-     * @throws MessagingException if there is a failure.
-     */
-    private void addAnyAttachments(final List<EmailAttachment<? extends DataSource>> attachments, final MimeMultipart multipart) throws MessagingException {
-        for (final EmailAttachment<? extends DataSource> attachment : attachments) {
-            final MimeBodyPart bodyPart = createAttachmentBodyPart(attachment);
-            multipart.addBodyPart(bodyPart);
-        }
-    }
-
-}

+ 0 - 60
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/SimpleAuthenticator.java

@@ -1,60 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.Authenticator;
-import jakarta.mail.PasswordAuthentication;
-
-/**
- * Performs simple authentication when the server requires it.
- */
-public class SimpleAuthenticator extends Authenticator {
-
-    private final String username;
-    private final String password;
-
-    /**
-     * Creates new SimpleAuthenticator for given username and password.
-     *
-     * @param username Username
-     * @param password Password
-     */
-    public SimpleAuthenticator(final String username, final String password) {
-        this.username = username;
-        this.password = password;
-    }
-
-    /**
-     * Return new {@link PasswordAuthentication} for given username and password.
-     *
-     * @return {@link PasswordAuthentication}
-     */
-    @Override
-    public PasswordAuthentication getPasswordAuthentication() {
-        return new PasswordAuthentication(username, password);
-    }
-}
-

+ 0 - 111
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/SmtpServer.java

@@ -1,111 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jakarta.mail.NoSuchProviderException;
-import jakarta.mail.Session;
-import jakarta.mail.Transport;
-
-import java.util.Properties;
-
-import static jodd.util.StringPool.TRUE;
-
-/**
- * Represents simple plain SMTP server for sending emails.
- */
-public class SmtpServer extends MailServer<SendMailSession> {
-
-    protected static final String PROTOCOL_SMTP = "smtp";
-
-    /**
-     * Default SMTP port
-     */
-    protected static final int DEFAULT_SMTP_PORT = 25;
-
-    // ---------------------------------------------------------------- create
-
-    public SmtpServer(final Builder builder) {
-        super(builder, DEFAULT_SMTP_PORT);
-    }
-
-    protected SmtpServer(final Builder builder, final int defaultPort) {
-        super(builder, defaultPort);
-    }
-
-    // ---------------------------------------------------------------- properties
-
-    @Override
-    protected Properties createSessionProperties() {
-        final Properties props = super.createSessionProperties();
-
-        props.setProperty(MAIL_TRANSPORT_PROTOCOL, PROTOCOL_SMTP);
-        props.setProperty(MAIL_HOST, host);
-        props.setProperty(MAIL_SMTP_HOST, host);
-        props.setProperty(MAIL_SMTP_PORT, String.valueOf(port));
-
-        if (authenticator != null) {
-            props.setProperty(MAIL_SMTP_AUTH, TRUE);
-        }
-
-        if (timeout > 0) {
-            final String timeoutValue = String.valueOf(timeout);
-            props.put(MAIL_SMTP_CONNECTIONTIMEOUT, timeoutValue);
-            props.put(MAIL_SMTP_TIMEOUT, timeoutValue);
-            props.put(MAIL_SMTP_WRITETIMEOUT, timeoutValue);
-        }
-
-        return props;
-    }
-
-    /**
-     * {@inheritDoc}
-     *
-     * @return {@link SendMailSession}
-     */
-    @Override
-    public SendMailSession createSession() {
-        final Session session = Session.getInstance(createSessionProperties(), authenticator);
-        final Transport mailTransport;
-        try {
-            mailTransport = getTransport(session);
-        } catch (final NoSuchProviderException nspex) {
-            throw new MailException(nspex);
-        }
-        return new SendMailSession(session, mailTransport);
-    }
-
-    /**
-     * Get the {@link Transport} for {@link Session}.
-     *
-     * @param session The {@link SendMailSession}.
-     * @return SMTP {@link Transport}.
-     * @throws NoSuchProviderException If provider for the given protocol is not found.
-     */
-    protected Transport getTransport(final Session session) throws NoSuchProviderException {
-        return session.getTransport(PROTOCOL_SMTP);
-    }
-
-}

+ 0 - 105
bladex-saas-project/new-mail/src/main/java/com/fjhx/utils/mail/SmtpSslServer.java

@@ -1,105 +0,0 @@
-// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-package com.fjhx.utils.mail;
-
-import jodd.util.StringPool;
-
-import java.util.Properties;
-
-/**
- * Secure SMTP server (STARTTLS) for sending emails.
- */
-public class SmtpSslServer extends SmtpServer {
-
-    /**
-     * Default SMTP SSL port.
-     */
-    protected static final int DEFAULT_SSL_PORT = 465;
-    /**
-     * Defaults to {@code false}.
-     */
-    protected boolean startTlsRequired = false;
-
-    // ---------------------------------------------------------------- properties
-    /**
-     * Defaults to {@code false}. Google requires it to be false
-     */
-    protected boolean plaintextOverTLS = false;
-
-    public SmtpSslServer(final Builder builder) {
-        super(builder, DEFAULT_SSL_PORT);
-    }
-
-    /**
-     * Sets <code>mail.smtp.starttls.required</code>.
-     * <p>
-     * If the server doesn't support the STARTTLS command, or the command fails,
-     * the connect method will fail. Defaults to {@code false}.
-     *
-     * @param startTlsRequired If {@code true}, requires the use of the STARTTLS command.
-     * @return this
-     */
-    public SmtpSslServer startTlsRequired(final boolean startTlsRequired) {
-        this.startTlsRequired = startTlsRequired;
-        return this;
-    }
-
-    /**
-     * When enabled, <code>MAIL_SMTP_SOCKET_FACTORY_CLASS</code> will be not set,
-     * and Plaintext Authentication over TLS will be enabled.
-     *
-     * @param plaintextOverTLS {@code true} when plain text authentication over TLS should be enabled.
-     * @return this
-     */
-    public SmtpSslServer plaintextOverTLS(final boolean plaintextOverTLS) {
-        this.plaintextOverTLS = plaintextOverTLS;
-        return this;
-    }
-
-    @Override
-    protected Properties createSessionProperties() {
-        final Properties props = super.createSessionProperties();
-
-        props.setProperty(MAIL_SMTP_STARTTLS_REQUIRED,
-                startTlsRequired ? StringPool.TRUE : StringPool.FALSE);
-
-        props.setProperty(MAIL_SMTP_STARTTLS_ENABLE, StringPool.TRUE);
-
-        props.setProperty(MAIL_SMTP_SOCKET_FACTORY_PORT, String.valueOf(port));
-
-        props.setProperty(MAIL_SMTP_PORT, String.valueOf(port));
-
-        if (!plaintextOverTLS) {
-            props.setProperty(MAIL_SMTP_SOCKET_FACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
-        }
-
-        props.setProperty(MAIL_SMTP_SOCKET_FACTORY_FALLBACK, StringPool.FALSE);
-        props.setProperty(MAIL_HOST, host);
-
-        return props;
-    }
-
-}

+ 2 - 2
bladex-saas-project/saas-mail-grad-online/src/main/java/com/fjhx/mail/grad/service/impl/GrabMailLogicServiceImpl.java

@@ -1253,11 +1253,11 @@ public class GrabMailLogicServiceImpl implements IGrabMailLogicService {
         if (nameIndex != -1) {
             conName = true;
         }
-        if (part.isMimeType("text/html") && conName == false) {
+        if (part.isMimeType("text/html") && !conName) {
             // text/html 类型
             // bodyText.append((String) part.getContent());
             return (String) part.getContent();
-        } else if (part.isMimeType("text/plain") && conName == false) {
+        } else if (part.isMimeType("text/plain") && !conName) {
             // text/plain 类型
             // bodyText.append((String) part.getContent());
             return (String) part.getContent();

+ 2 - 1
bladex-saas-project/saas-mail-grad-online/src/main/java/com/fjhx/mail/grad/service/impl/GrabMailServiceImpl.java

@@ -216,7 +216,8 @@ public class GrabMailServiceImpl implements IGrabMailService {
         // 官方文件夹map
         Map<String, String> officialFolderMap = new HashMap<>();
         if (CollectionUtils.isNotEmpty(folders)) {
-            officialFolderMap = folders.stream().collect(Collectors.toMap(MailFolder::getAncestorsName, MailFolder::getId, (key1, key2) -> key2));
+            officialFolderMap = folders.stream().collect(
+                    Collectors.toMap(MailFolder::getAncestorsName, MailFolder::getId, (key1, key2) -> key2));
             List<String> strList = folders.stream().map(MailFolder::getAncestorsName).distinct().collect(Collectors.toList());
             folderNamesList.addAll(strList);
         }