java收取邮件时,内容中的图片变附件处理
问题描述
一封邮件如果内嵌图片(非附件形式),那么在接收到的html邮件内容中,该内嵌图片也会以附件的形式被接收到,这时候如果不做特殊处理,html内容中的图片就会丢失 导致邮件显示不正常;
本文的做法是 使用javaMail接收邮件并取出附件上传到云端,再将上传后的url替换到html内容中。
上关键部分代码
// 解析Message对象中的附件
private static void getAttachmentAsStream(Part part, int times) throws MessagingException, IOException {
if (--times <= 0){
throw new CustomException("获取邮件附件,递归超过最大限制次数");
}
if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent(); //复杂体邮件
//复杂体邮件包含多个邮件体
int partCount = multipart.getCount();
for (int i = 0; i < partCount; i++) {
//获得复杂体邮件中其中一个邮件体
BodyPart bodyPart = multipart.getBodyPart(i);
//某一个邮件体也有可能是由多个邮件体组成的复杂体
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE))) {
// 匹配到的附件
MailAttachment mailAttachment = getAttach(bodyPart, disposition);
} else if (bodyPart.isMimeType("multipart/*")) {
getAttachmentAsStream(bodyPart, times);
} else {
String contentType = bodyPart.getContentType();
if (contentType.contains("name") || contentType.contains("application")) {
// 匹配到的附件
disposition = Part.INLINE;
MailAttachment mailAttachment = getAttach(bodyPart, disposition);
}
}
}
} else if (part.isMimeType("message/rfc822")) {
getAttachmentAsStream((Part) part.getContent(), times);
}
}
private static MailAttachment getAttach(BodyPart bodyPart, String disposition) throws MessagingException, IOException {
InputStream is = bodyPart.getInputStream();
String fileName = decodeText(bodyPart.getFileName());
// 附件的CID
String contentID = ((MimePart) bodyPart).getContentID();
if (contentID != null){
if(contentID.startsWith("<") && contentID.endsWith(">")){
contentID = contentID.substring(1, contentID.length() -1);
}
}
MailAttachment attachment = new MailAttachment(fileName, is, disposition);
attachment.setType(bodyPart.getDisposition());
attachment.setCid(contentID);
attachment.setType(disposition);
return attachment;
}
说明
邮件html中如果有图片的话将会显示<img src="cid:aaaaaa">
,其中aaaaaa就是cid,这个值可以通过上面代码中的getAttach
方法中获取到,将bodyPart强转成MimePart
对象后,调用getContentID方法。
后续将附件上传,返回的url替换html中的cid:aaaaaa就可以了。