Bläddra i källkod

fix: 下载乱码解决

chenjianhua 6 månader sedan
förälder
incheckning
ff3f2551ac

+ 31 - 5
service-base/src/main/java/com/simuwang/base/common/util/EmailUtil.java

@@ -66,7 +66,8 @@ public class EmailUtil {
             if ("String".equals(contentClass)) {
                 // 文件名 = 邮件主题 + 邮件日期
                 String fileName = emailTitle + "_" + emailDate + ".html";
-                emailContentInfoDTO = collectTextPart(part, partContent, filePath, fileName);
+                String content = partContent.toString();
+                emailContentInfoDTO = collectTextPart(part, content, filePath, fileName);
             } else if ("BASE64DecoderStream".equals(contentClass)) {
                 if (StrUtil.isNotBlank(part.getFileName())) {
                     String fileName = MimeUtility.decodeText(part.getFileName());
@@ -98,7 +99,8 @@ public class EmailUtil {
                     if ("String".equals(contentClass)) {
                         // 文件名 = 邮件主题 + 邮件日期
                         String fileName = emailTitle + "_" + emailDate + ".html";
-                        emailContentInfoDTO = collectTextPart(part, partContent, filePath, fileName);
+                        String content = partContent.toString();
+                        emailContentInfoDTO = collectTextPart(part, content, filePath, fileName);
                     }
                 }
             }
@@ -157,7 +159,7 @@ public class EmailUtil {
      * @param fileName    文件名
      * @return 采集到邮件正文(html格式包含table标签)
      */
-    public static EmailContentInfoDTO collectTextPart(MimeBodyPart part, Object partContent, String filePath, String fileName) {
+    public static EmailContentInfoDTO collectTextPart(MimeBodyPart part, String partContent, String filePath, String fileName) {
         EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
         try {
             if ((part.getContentType().contains("text/html") || part.getContentType().contains("TEXT/HTML"))) {
@@ -169,6 +171,17 @@ public class EmailUtil {
                             saveFile.getParentFile().mkdirs();
                             saveFile.getParentFile().setExecutable(true);
                         }
+                    }
+                    try{
+                        //获取邮件编码
+                        String contentType = part.getContentType();
+                        if(contentType.indexOf("charset=") != -1){
+                            contentType = contentType.substring(contentType.indexOf("charset=")+8,contentType.length());
+                            FileUtil.writeFile(new File(savePath), partContent.toString(),contentType);
+                        }else{
+                            FileUtil.writeFile(savePath, partContent.toString());
+                        }
+                    }catch (Exception e){
                         FileUtil.writeFile(savePath, partContent.toString());
                     }
                     emailContentInfoDTO.setFileName(fileName);
@@ -258,7 +271,21 @@ public class EmailUtil {
     public static void senEmail(MailboxInfoDTO mailboxInfoDTO, String emails, File file, JavaMailSender javaMailSender,String htmlText) throws Exception {
         logger.info("send email begin .........");
         // 根据Session 构建邮件信息
-        MimeMessage message = javaMailSender.createMimeMessage();
+        //	创建一个配置文件,并保存
+        Properties props = new Properties();
+        //	SMTP服务器连接信息
+        props.put("mail.smtp.host", mailboxInfoDTO.getHost());
+        props.put("mail.smtp.port", mailboxInfoDTO.getPort());
+        props.put("mail.smtp.auth", "true");
+        props.put("mail.smtp.starttls.enale", "true");
+        Session session = Session.getInstance(props,new Authenticator() {
+            @Override
+            protected PasswordAuthentication getPasswordAuthentication() {
+                return new PasswordAuthentication(mailboxInfoDTO.getAccount(),mailboxInfoDTO.getPassword());
+            }
+        });
+        // 根据Session 构建邮件信息
+        MimeMessage message = new MimeMessage(session);;
         // 创建邮件发送者地址
         Address from = new InternetAddress(mailboxInfoDTO.getAccount());
         String[] emailArr = emails.split(";");
@@ -296,5 +323,4 @@ public class EmailUtil {
         // 发送邮件
         javaMailSender.send(message);
     }
-
 }

+ 10 - 31
service-daq/src/main/java/com/simuwang/daq/service/EmailParseService.java

@@ -28,9 +28,7 @@ import com.simuwang.base.pojo.dto.report.ReportData;
 import com.simuwang.base.pojo.dto.report.ReportParseStatus;
 import com.simuwang.base.pojo.dto.report.ReportParserParams;
 import com.simuwang.base.pojo.valuation.CmValuationTableAttribute;
-import com.simuwang.base.pojo.vo.EmailParseDataViewVO;
-import com.simuwang.base.pojo.vo.EmailParseFailAnalysisVO;
-import com.simuwang.base.pojo.vo.NameValueVO;
+import com.simuwang.base.pojo.vo.*;
 import com.simuwang.daq.components.report.parser.ReportParser;
 import com.simuwang.daq.components.report.parser.ReportParserFactory;
 import com.simuwang.daq.components.report.writer.ReportWriter;
@@ -396,13 +394,11 @@ public class EmailParseService {
             registerNumber = matcher.group();
         }
         // 类型识别---先识别季度报告,没有季度再识别年度报告,最后识别月报
-        ReportType reportType = null;
+        ReportType reportType = ReportType.MONTHLY;
         if (StrUtil.containsAny(fileName, ReportType.QUARTERLY.getPatterns())) {
             reportType = ReportType.QUARTERLY;
         } else if (StrUtil.containsAny(fileName, ReportType.ANNUALLY.getPatterns())) {
             reportType = ReportType.ANNUALLY;
-        } else if (StrUtil.containsAny(fileName, ReportType.MONTHLY.getPatterns())) {
-            reportType = ReportType.MONTHLY;
         }
         // 解析器--如果开启python解析则直接调用python接口,否则根据文件后缀获取对应解析器
         ReportParserFileType fileType;
@@ -412,23 +408,13 @@ public class EmailParseService {
             String fileSuffix = StrUtil.subAfter(fileName, ".", true);
             fileType = ReportParserFileType.getBySuffix(fileSuffix);
         }
-        if (fileType == null) {
-            result.setStatus(ReportParseStatus.NO_SUPPORT_TEMPLATE.getCode());
-            result.setMsg(StrUtil.format(ReportParseStatus.NO_SUPPORT_TEMPLATE.getMsg(), fileName));
-            return result;
-        }
-        // 不是定期报告的判断逻辑放在不支持的格式下面
-        if (reportType == null) {
-            result.setStatus(ReportParseStatus.NOT_A_REPORT.getCode());
-            result.setMsg(StrUtil.format(ReportParseStatus.NOT_A_REPORT.getMsg(), fileName));
-            return result;
-        }
         // 解析报告
+        ReportParserParams params = null;
         ReportData reportData = null;
         StopWatch parserWatch = new StopWatch();
         parserWatch.start();
         try {
-            ReportParserParams params = ReportParserParams.builder().fileId(fileId).filename(fileName)
+            params = ReportParserParams.builder().fileId(fileId).filename(fileName)
                     .filepath(emailContentInfoDTO.getFilePath()).registerNumber(registerNumber).build();
             ReportParser<ReportData> instance = this.reportParserFactory.getInstance(reportType, fileType);
             reportData = instance.parse(params);
@@ -436,17 +422,17 @@ public class EmailParseService {
             result.setMsg("报告解析成功");
             result.setData(reportData);
         } catch (ReportParseException e) {
-            log.error("解析失败\n{}", e.getMsg());
+            log.error("报告{}解析失败\n{}", params, e.getMsg());
             result.setStatus(e.getCode());
             result.setMsg(e.getMsg());
         } catch (Exception e) {
-            log.error("解析失败\n{}", ExceptionUtil.stacktraceToString(e));
+            log.error("报告{}解析失败\n{}", params, ExceptionUtil.stacktraceToString(e));
             result.setStatus(ReportParseStatus.PARSE_FAIL.getCode());
             result.setMsg(StrUtil.format(ReportParseStatus.PARSE_FAIL.getMsg(), e.getMessage()));
         } finally {
             parserWatch.stop();
             if (log.isInfoEnabled()) {
-                log.info("报告{}解析结果为{},耗时{}ms", fileName, reportData, parserWatch.getTotalTimeMillis());
+                log.info("报告{}解析结果为{},耗时{}ms", params, reportData, parserWatch.getTotalTimeMillis());
             }
         }
         // 保存报告解析结果
@@ -457,11 +443,11 @@ public class EmailParseService {
                 ReportWriter<ReportData> instance = this.reportWriterFactory.getInstance(reportType);
                 instance.write(reportData);
             } catch (Exception e) {
-                log.error("报告{}结果保存失败\n{}", fileName, ExceptionUtil.stacktraceToString(e));
+                log.error("报告{}结果保存失败\n{}", params, ExceptionUtil.stacktraceToString(e));
             } finally {
                 writeWatch.stop();
                 if (log.isInfoEnabled()) {
-                    log.info("报告{}解析结果保存完成,耗时{}ms", fileName, writeWatch.getTotalTimeMillis());
+                    log.info("报告{}解析结果保存完成,耗时{}ms", params, writeWatch.getTotalTimeMillis());
                 }
             }
         }
@@ -860,14 +846,7 @@ public class EmailParseService {
                 // 2.邮件只有正文
                 if (content instanceof String) {
                     EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
-                    try {
-                        //获取邮件编码
-                        String contentType = message.getContentType();
-                        contentType = contentType.substring(contentType.indexOf("charset=") + 8, contentType.length());
-                        emailContentInfoDTO.setEmailContent(new String(content.toString().getBytes(contentType), "UTF-8"));
-                    } catch (Exception e) {
-                        emailContentInfoDTO.setEmailContent(content.toString());
-                    }
+                    emailContentInfoDTO.setEmailContent(content.toString());
                     emailContentInfoDTO.setEmailDate(emailDateStr);
                     emailContentInfoDTO.setEmailTitle(message.getSubject());
                     String fileName = message.getSubject() + DateUtil.format(emailDate, DateConst.YYYYMMDDHHMMSS24);

+ 4 - 6
service-manage/src/main/java/com/simuwang/manage/api/email/ParseEmailController.java

@@ -2,6 +2,7 @@ package com.simuwang.manage.api.email;
 
 import com.simuwang.base.common.support.MybatisPage;
 import com.simuwang.base.common.util.EncodeUtil;
+import com.simuwang.base.common.util.FileUtil;
 import com.simuwang.base.pojo.dto.query.EmailFileQuery;
 import com.simuwang.base.pojo.dto.query.EmailParseQuery;
 import com.simuwang.base.pojo.vo.*;
@@ -13,12 +14,14 @@ import com.smppw.common.pojo.enums.TimeRange;
 import jakarta.servlet.ServletOutputStream;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
+import org.apache.commons.io.FileUtils;
 import org.apache.ibatis.annotations.Param;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
+import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -112,15 +115,10 @@ public class ParseEmailController{
     public void downloadEmailFile(@RequestBody FileIdVO fileId,HttpServletResponse response, HttpServletRequest request){
         try {
             EmailFileInfoVO emailFileInfoVO = parseEmailService.getEmailFileById(fileId.getFileId());
-            FileInputStream fileInputStream = new FileInputStream(emailFileInfoVO.getFilePath());
             response.setContentType("application/octet-stream");
             response.addHeader("Content-Disposition", "attachment;filename=" + EncodeUtil.encodeUTF8(emailFileInfoVO.getFileName()));
             ServletOutputStream outputStream = response.getOutputStream();
-            byte[] b = new byte[1024];
-            while(fileInputStream.read(b) > 0){
-                outputStream.write(b);
-            }
-            fileInputStream.close();
+            FileUtils.copyFile(new File(emailFileInfoVO.getFilePath()),outputStream);
             outputStream.flush();
             outputStream.close();
         } catch (IOException e) {

+ 5 - 15
service-manage/src/main/java/com/simuwang/manage/service/impl/CompanyEmailConfigServiceImpl.java

@@ -61,16 +61,6 @@ public class CompanyEmailConfigServiceImpl implements CompanyEmailConfigService
 
     @Value("${email.file.path}")
     private String path;
-    @Value("${spring.mail.username}")
-    private String account;
-    @Value("${spring.mail.password}")
-    private String password;
-    @Value("${spring.mail.host}")
-    private String host;
-    @Value("${spring.mail.port}")
-    private String port;
-    @Value("${spring.mail.protocol}")
-    private String protocol;
     @Override
     public ResultVo saveCompanyEmailConfig(List<CompanyEmailConfigVO> companyEmailConfigVOS) {
         ResultVo vo = new ResultVo(com.smppw.common.pojo.enums.status.ResultCode.SAVE_SUCCESS);
@@ -212,11 +202,11 @@ public class CompanyEmailConfigServiceImpl implements CompanyEmailConfigService
 
     private MailboxInfoDTO getFromEmailInfo(){
         MailboxInfoDTO dto = new MailboxInfoDTO();
-        dto.setAccount(account);
-        dto.setProtocol(protocol);
-        dto.setPassword(password);
-        dto.setPort(port);
-        dto.setHost(host);
+        dto.setAccount(sysConfigMapper.selectConfigByKey("sender.email"));
+        dto.setProtocol(sysConfigMapper.selectConfigByKey("sender.protocol"));
+        dto.setPassword(sysConfigMapper.selectConfigByKey("sender.password"));
+        dto.setPort(sysConfigMapper.selectConfigByKey("sender.port"));
+        dto.setHost(sysConfigMapper.selectConfigByKey("sender.host"));
         return dto;
     }