Ver Fonte

邮件服务

24282 há 2 anos atrás
pai
commit
f528233a90

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

@@ -75,4 +75,9 @@ public class Mailbox implements Serializable {
      */
     private Integer smtpPort;
 
+    /**
+     * 更新时间
+     */
+    private Date updateTime;
+
 }

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

@@ -15,6 +15,7 @@ import com.fjhx.service.MailboxService;
 import com.fjhx.utils.EmailUtil;
 import com.sun.mail.imap.IMAPMessage;
 import com.sun.mail.imap.IMAPStore;
+import com.sun.mail.util.MailConnectException;
 import lombok.AllArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.springblade.core.tool.utils.ThreadUtil;
@@ -25,10 +26,8 @@ import org.springframework.stereotype.Service;
 import javax.annotation.PostConstruct;
 import javax.mail.*;
 import javax.mail.internet.InternetAddress;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Objects;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
 
@@ -56,6 +55,8 @@ public class CoreServiceImpl {
     // 初始化同步邮件天数
     private static final int initDay = 7;
 
+    private static final Map<String, Integer> map = new ConcurrentHashMap<>();
+
     @AllArgsConstructor
     class Task implements Runnable {
 
@@ -208,6 +209,8 @@ public class CoreServiceImpl {
                 }
             }
 
+        } catch (AuthenticationFailedException | MailConnectException exception) {
+            disableMailRead(mailbox.getId());
         } catch (Exception e) {
             log.error("邮件同步出错,邮箱信息:{}", JSON.toJSONString(mailbox), e);
         } finally {
@@ -223,6 +226,19 @@ public class CoreServiceImpl {
         }
     }
 
+    private void disableMailRead(String mailboxId) {
+        map.merge(mailboxId, 1, Integer::sum);
+
+        Integer num = map.get(mailboxId);
+        if (num >= 3) {
+            mailboxService.update(Wrappers.<Mailbox>lambdaUpdate()
+                    .eq(Mailbox::getId, mailboxId)
+                    .set(Mailbox::getStatus, 1)
+                    .set(Mailbox::getUpdateTime, new Date()));
+            map.remove(mailboxId);
+        }
+    }
+
     /**
      * 拉取邮件
      */
@@ -273,6 +289,9 @@ public class CoreServiceImpl {
             mailInfo.setFolderName(mailFolder.getName());
             mailInfo.setSendDate(receivedDate);
             mailInfo.setCreateTime(new Date());
+            mailInfo.setAddressSync(0);
+            mailInfo.setMessageSync(0);
+            mailInfo.setAttachmentSync(0);
 
             // 保存发件人信息
             Address[] addresses = message.getFrom();

+ 30 - 9
bladex-saas-project/new-mail/src/main/java/com/fjhx/service/impl/MailFolderServiceImpl.java

@@ -11,6 +11,7 @@ import com.fjhx.service.*;
 import com.fjhx.utils.EmailUtil;
 import com.fjhx.vo.MailDetailsVo;
 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.springblade.core.log.exception.ServiceException;
@@ -23,10 +24,7 @@ import org.springframework.stereotype.Service;
 
 import javax.mail.*;
 import javax.mail.internet.MimeUtility;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
+import java.io.*;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Objects;
@@ -75,14 +73,16 @@ public class MailFolderServiceImpl extends ServiceImpl<MailFolderMapper, MailFol
         Integer attachmentSync = mailInfo.getAttachmentSync();
 
         if (ObjectUtil.notEqual(messageSync, 1) || ObjectUtil.notEqual(addressSync, 1) || ObjectUtil.notEqual(attachmentSync, 1)) {
+
             Mailbox mailbox = mailboxService.getById(mailInfo.getMailboxId());
             IMAPStore imapStore = null;
             IMAPFolder folder = null;
+
             try {
                 imapStore = EmailUtil.getIMAPStore(mailbox.getMailHost(), mailbox.getMailboxName(), mailbox.getMailboxPwd());
                 folder = (IMAPFolder) imapStore.getFolder(mailInfo.getFolderName());
                 folder.open(Folder.READ_ONLY);
-                Message message = folder.getMessage(mailInfo.getMessageNumber());
+                IMAPMessage message = (IMAPMessage) folder.getMessage(mailInfo.getMessageNumber());
 
                 // 同步地址
                 if (ObjectUtil.notEqual(addressSync, 1)) {
@@ -165,12 +165,15 @@ public class MailFolderServiceImpl extends ServiceImpl<MailFolderMapper, MailFol
         if (part.isMimeType("text/plain")) {
             addPlain(part, message);
         }
+
         // 正文:html格式
         else if (part.isMimeType("text/html")) {
             addHtml(part, message);
         }
+
         // 大对象
         else if (part.isMimeType("multipart/*")) {
+
             // 复杂体邮件
             Multipart multipart = (Multipart) part.getContent();
 
@@ -178,8 +181,10 @@ public class MailFolderServiceImpl extends ServiceImpl<MailFolderMapper, MailFol
             int partCount = multipart.getCount();
 
             for (int i = 0; i < partCount; i++) {
+
                 // 获得复杂体邮件中其中一个邮件体
                 BodyPart bodyPart = multipart.getBodyPart(i);
+
                 // 某一个邮件体也有可能是由多个邮件体组成的复杂体
                 String disposition = bodyPart.getDisposition();
 
@@ -202,13 +207,14 @@ public class MailFolderServiceImpl extends ServiceImpl<MailFolderMapper, MailFol
                 else if (bodyPart.isMimeType("multipart/*")) {
                     saveMessageAndAttachment(mailDetailsVo, bodyPart);
                 }
+
                 // 其他类型
                 else {
                     String contentType = bodyPart.getContentType();
                     if (contentType.contains("name") || contentType.contains("application")) {
                         addFile(bodyPart, mailAttachmentList, message.getMailInfoId());
                     } else {
-                        log.error("未知文件格式:{} ,待解析", contentType);
+                        log.error("未知文件格式:{} ,邮件id:{},待解析", contentType, message.getMailInfoId());
                     }
                 }
 
@@ -220,7 +226,7 @@ public class MailFolderServiceImpl extends ServiceImpl<MailFolderMapper, MailFol
         }
         // 未知格式
         else {
-            log.error("未知文件格式:{} ,待解析", part.getContentType());
+            log.error("未知文件格式:{} ,邮件id:{},待解析", part.getContentType(), message.getMailInfoId());
         }
 
     }
@@ -277,12 +283,24 @@ public class MailFolderServiceImpl extends ServiceImpl<MailFolderMapper, MailFol
      */
     private String uploadFile(InputStream is, String fileName) {
 
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        BufferedInputStream bis = new BufferedInputStream(is);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        BufferedOutputStream bos = new BufferedOutputStream(baos);
+
         try {
+            int len;
+
+            while ((len = bis.read()) != -1) {
+                bos.write(len);
+                bos.flush();
+            }
+
             bos.write(is.read());
+
+            // 上次附件至华为云
             ObsUpload obsUpload = new ObsUpload();
             obsUpload.setFileName(fileName);
-            obsUpload.setBytes(bos.toByteArray());
+            obsUpload.setBytes(baos.toByteArray());
             R<JSONObject> jsonObjectR = obsClient.uploadHuaWei(obsUpload);
             if (jsonObjectR.isSuccess()) {
                 JSONObject data = jsonObjectR.getData();
@@ -290,8 +308,11 @@ public class MailFolderServiceImpl extends ServiceImpl<MailFolderMapper, MailFol
             }
         } catch (Exception e) {
             log.error("上传文件出错", e);
+            throw new ServiceException("获取附件出现错误");
         } finally {
             IoUtil.close(bos);
+            IoUtil.close(baos);
+            IoUtil.close(bis);
             IoUtil.close(is);
         }
         return null;

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

@@ -31,13 +31,12 @@ public class EmailUtil {
 
     static {
         props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
+        session = Session.getInstance(props);
 
         map.put("name", "fjhx");
         map.put("version", "1.0.0");
         map.put("vendor", "myClient");
         map.put("support-email", "fjhx@fjhx.com");
-
-        session = Session.getInstance(props);
     }
 
     /**
@@ -46,10 +45,8 @@ public class EmailUtil {
     public static IMAPStore getIMAPStore(String host, String user, String password) throws MessagingException {
         IMAPStore store = (IMAPStore) session.getStore("imap");
 
-        synchronized (EmailUtil.class) {
-            store.id(map);
-            store.connect(host, 993, user, password);
-        }
+        store.connect(host, 993, user, password);
+        store.id(map);
 
         return store;
     }
@@ -59,7 +56,7 @@ public class EmailUtil {
      */
     public static List<MailFolder> createMailFolderList(IMAPStore store, String mailboxId) throws MessagingException {
         IMAPFolder folder = (IMAPFolder) store.getDefaultFolder();
-        IMAPFolder[] folders = (IMAPFolder[]) folder.list();
+        Folder[] folders = folder.list();
         List<MailFolder> mailFolderList = new ArrayList<>();
         addMailFolderList(mailFolderList, folders, mailboxId);
         return mailFolderList;
@@ -121,7 +118,9 @@ public class EmailUtil {
     //     // sendMail("imap.163.com", "l17689260703@163.com", "WFARTAFVZZKOVNUF", sendDto);
     // }
 
-
+    /**
+     * 发送邮件
+     */
     public static void sendMail(String host, String user, String password, SendDto sendDto) throws Exception {
 
         // QQ存在一个特性设置SSL加密
@@ -172,6 +171,7 @@ public class EmailUtil {
         if (ObjectUtil.isNotEmpty(replyTo)) {
             mimeMessage.setReplyTo(getAddresses(replyTo));
         }
+
         // 邮件标题
         mimeMessage.setSubject(sendDto.getSubject());
 
@@ -197,6 +197,7 @@ public class EmailUtil {
             }
         }
 
+        // 添加邮件内容
         mimeMessage.setContent(mimeMultipart);
 
         // 连接服务器
@@ -236,11 +237,11 @@ public class EmailUtil {
     }
 
 
-    private static void addMailFolderList(List<MailFolder> mailFolderList, IMAPFolder[] folders, String mailboxId) throws MessagingException {
-        for (IMAPFolder folder : folders) {
+    private static void addMailFolderList(List<MailFolder> mailFolderList, Folder[] folders, String mailboxId) throws MessagingException {
+        for (Folder folder : folders) {
             int type = folder.getType();
             if (type == 2) {
-                addMailFolderList(mailFolderList, (IMAPFolder[]) folder.list(), mailboxId);
+                addMailFolderList(mailFolderList, folder.list(), mailboxId);
             } else if (type == 3) {
                 MailFolder mailFolder = new MailFolder();
                 mailFolder.setId(IdWorker.getId());