主要使用的还是jodd 的代码, CommonEmail类下添加了图片正文的存放,目的是在保存正文时直接把图片转码成base64和正文一起保存在一个html文件中
Map<String, String> imgs = new HashMap<String, String>();
public void addImgs(String contentID,String fileName) {
imgs.put(contentID, fileName);
}
public Map<String, String> getImgs() {
return imgs;
}
保存时的代码
//替换原文中的图片,原始图片标签为<img src="cid:image001.jpg@01D24963.3B4B8280">
String content ="";
Map<String, String> imgs=remail.getImgs();
for (String contentId : imgs.keySet()) {
String replacedText = "src=\"cid:" + contentId.replace("<", "").replace(">", "");
File imgFile = new File(imgs.get(contentId));
String extend=FileUtils.getExtend(imgFile.getName());
try {
BufferedImage bi = ImageIO.read(imgFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, extend, baos);
//经测试转换的图片是格式这里就什么格式,否则会失真
byte[] imgbytes = baos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
String imgBinaryData=encoder.encode(imgbytes).trim().replaceAll("\n", "").replaceAll("\r", "");
content = content.replace(replacedText, " src=\"data:image/"+extend+";base64,"+imgBinaryData);
} catch (IOException e) {
e.printStackTrace();
}
}
解析主体代码如下:
protected static void processPart(ReceivedEmail email, Part part) {
String contentType = "";
try {
Object content = part.getContent();
contentType = part.getContentType();
if (content instanceof String) {
String stringContent = (String) content;
String disposition = part.getDisposition();
if (disposition != null && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
String mimeType = extractMimeType(part.getContentType());
String fileName = part.getFileName();
String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
email.addAttachment(fileName, mimeType, contentId, stringContent.getBytes(JoddDefault.encoding));
} else {
email.addMessage(stringContent, extractMimeType(contentType), extractEncoding(contentType));
}
} else if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
int count = mp.getCount();
for (int i = 0; i < count; i++) {
Part innerPart = mp.getBodyPart(i);
processPart(email, innerPart);
}
} else if (content instanceof InputStream) {
if (part.isMimeType("image/*") && part.getHeader("Content-ID") != null) {
String contentID = ((String[]) part.getHeader("Content-ID"))[0];
InputStream in = (InputStream) content;
// 文件下载开始
String uuid = UUID.randomUUID().toString();
String fileName = part.getFileName();
if (fileName.indexOf("=?") != -1 && fileName.indexOf("?=") != -1) {
fileName = MimeUtility.decodeText(fileName);
}
String extend = FileUtils.getExtend(fileName);
if (!StrUtil.isContainsBySign("bmp,jpg,jpeg,png,gif", extend)) {
extend = "jpg";
}
try {
String saveFileName = FileService.root + FileService.UPLOAD_SAVE_PATH
+ RootPathEnum.FilePathEnum.EMAIL_CONTENT_IMGS_PATH.getMainType() + uuid + "." + extend;
FileUtils.writeFile(saveFileName, in);
email.addImgs(contentID, saveFileName);
} catch (Exception e) {
// TODO Auto-generated catch block
log.info("出错的邮件的主题: " + email.getSubject());
log.error("邮件正文图片保存失败!");
log.error("文件名:" + fileName);
e.printStackTrace();
}
} else if (content instanceof BASE64DecoderStream) {
String contentID = "";
if (part.getHeader("Content-ID") == null) {
String fileName = part.getFileName();
String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
String mimeType = extractMimeType(part.getContentType());
BASE64DecoderStream is = (BASE64DecoderStream) content;
FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
StreamUtil.copy(is, fbaos);
email.addAttachment(MessyCodeCheck.mailGarishAnalysis(fileName), mimeType, contentId,
fbaos.toByteArray());
} else {
contentID = ((String[]) part.getHeader("Content-ID"))[0];
BASE64DecoderStream base64Stream = (BASE64DecoderStream) content;
String uuid = UUID.randomUUID().toString();
String fileName = part.getFileName();
String extend = FileUtils.getExtend(fileName);
if (!StrUtil.isContainsBySign("bmp,jpg,jpeg,png,gif", extend)) {
extend = "jpg";
}
try {
String saveFileName = FileService.root + FileService.UPLOAD_SAVE_PATH
+ RootPathEnum.FilePathEnum.EMAIL_CONTENT_IMGS_PATH.getMainType() + uuid + "."
+ extend;
FileUtils.writeFile(saveFileName, base64Stream);
email.addImgs(contentID, saveFileName);
// log.info("图片正文路径: " + saveFileName);
} catch (Exception e) {
// TODO Auto-generated catch block
log.info("出错的邮件的主题: " + email.getSubject());
log.error("邮件正文图片保存失败!");
log.error("文件名:" + fileName);
e.printStackTrace();
} finally {
base64Stream.close();
}
}
} else {
String fileName = part.getFileName();
String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
String mimeType = extractMimeType(part.getContentType());
InputStream is = (InputStream) content;
FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
StreamUtil.copy(is, fbaos);
email.addAttachment(MessyCodeCheck.mailGarishAnalysis(fileName), mimeType, contentId,
fbaos.toByteArray());
}
} else if (part.isMimeType("message/rfc822")) {
String mimeType = extractMimeType(part.getContentType());
String fileName = part.getFileName();
String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
InputStream is = part.getInputStream();
FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
StreamUtil.copy(is, fbaos);
email.addAttachment(fileName, mimeType, contentId, fbaos.toByteArray());
} else if (content instanceof BufferedImage) {
if (part.isMimeType("image/*") && part.getHeader("Content-ID") != null) {
String contentID = ((String[]) part.getHeader("Content-ID"))[0];
BufferedImage bufferedImage = (BufferedImage) content;
// 文件下载开始
String uuid = UUID.randomUUID().toString();
String fileName = part.getFileName();
String extend = FileUtils.getExtend(fileName);
if (!StrUtil.isContainsBySign("bmp,jpg,jpeg,png,gif", extend)) {
extend = "jpg";
}
try {
String saveFileName = FileService.root + FileService.UPLOAD_SAVE_PATH
+ RootPathEnum.FilePathEnum.EMAIL_CONTENT_IMGS_PATH.getMainType() + uuid + "." + extend;
ImageIO.write(bufferedImage, extend, new File(saveFileName));
email.addImgs(contentID, saveFileName);
// log.info("图片正文路径: " + saveFileName);
} catch (Exception e) {
// TODO Auto-generated catch block
log.info("出错的邮件的主题: " + email.getSubject());
log.error("邮件正文图片保存失败!");
log.error("文件名:" + fileName);
e.printStackTrace();
}
} else {
String mimeType = extractMimeType(part.getContentType());
String fileName = part.getFileName();
String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
InputStream is = part.getInputStream();
FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
StreamUtil.copy(is, fbaos);
email.addAttachment(fileName, mimeType, contentId, fbaos.toByteArray());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
log.info("出错的邮件的主题: " + email.getSubject());
e.printStackTrace();
}
}
ReceivedEmail是jodd 的类,在方法里只是起到临时存储的作用。
StrUtil.isContainsBySign()方法是判断第一个参数中是否包含第二个参数,逗号是分隔符,
FileUtils.writeFile()方法是指定文件路径写入文件流,
MessyCodeCheck.mailGarishAnalysis是处理文件名称乱码的方法
这种解析方法依赖jodd,如果不用jodd就要仔细挑出来每个步骤的类型判断了。
目前来说处理公司收到的各种不同方式写出来的邮件没有出现漏掉内容的情况。如有遗漏还请指出,谢谢。