文件控件上传.msg格式文件,达到预览效果

前端控件代码就介绍了,重点是解析文件。我是用了outlook-message-parser来解析文件。

代码展示

首先是maven依赖

<dependency><groupId>org.simplejavamail</groupId><artifactId>outlook-message-parser</artifactId><version>1.7.4</version>
</dependency>

其次代码

    /*** 解析MSG邮件,可以将邮件以HTML展示。* @param file MSG格式邮件的全路径* @return vo * @throws IOException IO异常*/public static EmailPreviewVo msgParseToPreview(File file) throws IOException {EmailPreviewVo vo = new EmailPreviewVo();OutlookMessageParser msgp = new OutlookMessageParser();OutlookMessage msg = msgp.parseMsg(file.getAbsolutePath());List<FileVo> attachList = new ArrayList<>();for(int i=0; i < msg.getOutlookAttachments().size(); i++) {/** TODO 注意:OutlookAttachment 是个接口有两个实现类,*  1)、OutlookFileAttachment  存在真实文件字节数据集*  2)、OutlookMsgAttachment 为.msg格式文件再次被递归解析*      目前没有好办法去获取到邮件附件为.msg格式真实文件,*/// .msg格式附件暂时忽略if (msg.getOutlookAttachments().get(i) instanceof OutlookMsgAttachment) {continue;}OutlookFileAttachment attachment = (OutlookFileAttachment) msg.getOutlookAttachments().get(i);String attachName = attachment.getFilename();File attachementFile = null;// 创建文件 可根据自己实际情况进行使用自己的方法/***  public static String getSuffix(String fileName) {*         if (fileName.contains(".")) {*             String suffix = fileName.substring(fileName.lastIndexOf("."));*             return trimilSpace(suffix.toLowerCase());*         }*         throw new AppException("文件没有后缀");*     }*/if (Utils.existSuffix(attachName)) {String suffix = Utils.getSuffix(attachName);attachementFile = Utils.createTmpFile(suffix);/***   public static String getTmpDir() {*         return System.getProperty("java.io.tmpdir");*    }*//***  public static File createTmpFile(String suffix) {*         return new File(getTmpDir(), UUID.randomUUID().toString().replace("-", "") + suffix);*     }*/} else {attachementFile = Utils.createTmpFileWithName(attachName);/***   public static File createTmpFileWithName(String fileName) {*         return new File(getTmpDir(), fileName);*     }*/}InputStream is = new ByteArrayInputStream(attachment.getData());org.apache.commons.io.FileUtils.copyInputStreamToFile(is, attachementFile);if (attachementFile != null) {FileVo fileVo = new FileVo();fileVo.setFileName(attachName);fileVo.setFileLength(attachementFile.length());fileVo.setFilePath(attachementFile.getAbsolutePath());attachList.add(fileVo);}}vo.setAttachments(attachList);// 内容 要处理下不然他会带有微软雅黑的样式,与原邮件样式不符/***org.jsoup.nodes.Document*org.jsoup.Jsoup*/Document doc = Jsoup.parse(msg.getConvertedBodyHTML());List<FileVo> newAttachList = new ArrayList<>();newAttachList.addAll(attachList);// 对邮件中图片进行处理Elements imgList = doc.select("img");if (imgList.size() > 0) {imgList.forEach(new Consumer<Element>() {@Overridepublic void accept(Element element) {String src = element.attr("src");if (src.indexOf("cid:") < 0) {return;}String imgAttach = src.substring(4);FileVo fileVo = null;for (FileVo tmp : attachList) {if (tmp.getDescription().equals(imgAttach)) {fileVo = tmp;break;}}if (fileVo == null) {return;}File attach = new File(fileVo.getFilePath());String base64 = null;InputStream in = null;try {in = new FileInputStream(attach);byte[] bytes=new byte[(int)attach.length()];in.read(bytes);base64 = Base64.getEncoder().encodeToString(bytes);} catch (Exception e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}if (StringUtils.isNotBlank(base64)) {String srcBase64 = "data:image/png;base64," + base64;element.attr("src", srcBase64);if(newAttachList!=null && newAttachList.size() > 0 && newAttachList.contains(fileVo)){newAttachList.remove(fileVo);}}}});}// 内容Elements bodyList = doc.select("body");if (bodyList.size() > 0) {Element bodyEle = bodyList.first();if (bodyEle.html().length() > 0) {vo.setContent(bodyEle.html());}}// 消息头信息vo.setSentDate(DateUtils.fmt(msg.getClientSubmitTime()));// 日期格式化,自己手动处理下vo.setFrom(msg.getFromEmail());vo.setTo(getMailUser(msg, msg.getDisplayTo().trim()));vo.setCc(getMailUser(msg, msg.getDisplayCc().trim()));vo.setSubject(msg.getSubject());return vo;}

处理收、抄人显示

/*** MSG 以名称获取真实收发抄邮件地址* @param msg OutlookMessage * @param parm 人员成名* @return 展示名称*/private static String getMailUser(OutlookMessage msg, String parm) {List<String> parmList = null;OutlookRecipient recipient = null;StringBuffer sb = new StringBuffer();if(StringUtils.isNotBlank(parm)){if (parm.contains(";")) {parmList = Arrays.asList(parm.split(";")).stream().map(s -> s.trim()).collect(Collectors.toList());for (int i = 0; i < parmList.size(); i++) {String value = parmList.get(i);if (msg != null && msg.getRecipients().size() > 0) {recipient = msg.getRecipients().stream().filter(e -> e.getName().equals(value)).collect(Collectors.toList()).get(0);sb.append(recipient.getName());sb.append(" <" + recipient.getAddress() + ">");if (i != (parmList.size() - 1)) {sb.append(",");}}}} else {recipient = msg.getRecipients().stream().filter(e -> e.getName().equals(parm)).collect(Collectors.toList()).get(0);sb.append(recipient.getName());sb.append(" <" + recipient.getAddress() + ">");}}return sb.toString();}

EmailPreviewVo 实体

public class EmailPreviewVo {private Long id;private String from;private String cc;private String to;private String subject;private String sentDate;private String content;private List<FileVo> attachments;
}

希望能起到帮助 Good luck

java 对Outlook保存的.Msg格式文件解析相关推荐

  1. mht 转换 html java,使用java将网页保存为mht格式(2)

    //设置网页正文 MimeBodyPart bp = new MimeBodyPart(); bp.setText(content, strEncoding); bp.addHeader(" ...

  2. 使用Java将HTML转成Word格式文件

    转载自  使用Java将HTML转成Word格式文件 import java.io.ByteArrayInputStream; import java.io.File; import java.io. ...

  3. 记事本TXT中文默认保存的ANSI格式文件乱码,一些软件菜单乱码,右键菜单某些乱码...

    记事本TXT中文默认保存的ANSI格式文件乱码,一些软件菜单乱码,右键菜单某些乱码 发现的乱码现象主要体现在WinRAR软件的右键菜单.记事本编辑打开的所有ANSI格式编码的文件.FlashFXP上传 ...

  4. FFmpeg4入门07:解码视频并保存为YUV格式文件

    上一篇我们解码并保存了其中的几帧确保解码过程和结果是对的.本篇我们将解码整个视频并保存为标准的YUV格式(YUV格式具体信息详见YUV格式介绍),我们就选YUV420P(I420)作为输出格式. 保存 ...

  5. 把python tkinter canvas中的图形图像保存为通用格式文件的5种方法

    在计算机上画图未完成,需要保存未完成图形以便以后继续,或者完成画图,要保存为通用格式文件,方便浏览.如使用python tkinter Canvas画图,其好像没有将图像保存通用格式文件的方法,但可以 ...

  6. 使用python 将稀疏矩阵保存为mtx格式文件

    使用scipy包 import scipy.sparse as sparse import scipy.io as sio import scipy.stats as stats import num ...

  7. outlook导出邮件(.msg)读取和解析

    @TOC 由outlook导出的邮件后缀.msg 文件读取,获取邮件内容提取有效数据 引入必要依赖 <dependency><groupId>org.simplejavamai ...

  8. 分布式.RPC-WebService入门案例(java实现,注解实现,xsd文件解析,wsdl文件解析)

     系列博文: 分布式.RPC调用-RMI & Hessian框架_闲猫的博客-CSDN博客 分布式.RPC-WebService三要素,三个规范, Soap协议_闲猫的博客-CSDN博客 分布 ...

  9. Java中[xxx:xxx,aaa:aaa]格式字符串解析

    Java中[xxx:xxx,aaa:aaa]格式字符串解析 String str = "[name:张三,age:18,phone:15888887777,email:15888887777 ...

最新文章

  1. python招聘笔试题_滴滴2020年春招笔试题分析(Python)
  2. 第一课 前言 学PHP就是为了做网站
  3. 关于TP框架的微信开发服务器配置TOKEN验证失败解决方案
  4. 【ORACLE 高可用】ORACLE STREAM 基于用户的流复制配置 案例
  5. NBU网络备份大全之oracle系统冷备份
  6. string 都不能作用于switch_谁带孩子争论不休?家庭教育谁也不能缺席,每个人的作用都不同...
  7. 《Effective Java读书笔记》--通用程序设计
  8. 无悔入华夏怎么一直显示服务器,无悔入华夏祭祀玩法怎么玩 无悔入华夏祭祀怎么触发?...
  9. 数据分析看关晓彤的招黑之路
  10. VS实用小工具(检测代码内存泄漏等问题)
  11. MyBatis官方文档
  12. 吴伯凡:VUCA时代的自我迭代
  13. (20210301未解决)error: chmod on /path/.git/config.lock failed: Operation not permitted
  14. 微信支付之App支付
  15. java基础知识面试题(41-95)
  16. STM32 ADC 单次模式、连续模式、扫描模式
  17. datagridview获取行中列的数据
  18. 前端axios下载excel文件(二进制)的处理方法
  19. CAB教程,国人写的
  20. 购物类App原型制作分享-Polyvore

热门文章

  1. Ubuntu安装etter
  2. 不动点迭代(Fixed Point Iteration)
  3. YTU-2324-约瑟夫环
  4. PMP考试 变更管理专题
  5. 信息系统项目管理师 第七章-项目成本管理
  6. CSAPP datalab实验
  7. 【SRE笔记 2022.8.16 Linux命令基础01】
  8. 豆瓣8.0分,尺度堪比色戒,一部让人绝望的电影
  9. python读取二维数组的行列数_Python获取二维数组的行列数的2种方法
  10. 计算机毕业设计ssm电脑销售管理系统