[英]How to receive and distinguish between regular attachments and inline attachments in Apache Commons Email 1.4
目前我们收到一封电子邮件,它被解析
MimeMessageParser mimeMessageParser = parse(message);
然后拉出附件
if (mimeMessageParser.hasAttachments()) {
List<DataSource> attachments = mimeMessageParser.getAttachmentList();
for (DataSource dataSource : attachments) {
saveAttachment(dataSource, subjectLineProperties, documentToUpload, firstHeaders);
}
}
问题是 getAttachmentList 也返回内嵌图像,如企业徽标的签名行,我们不想将内嵌图像作为附件拉出。 我们只想要实际的电子邮件附件。 ATTACHMENT 与 INLINE,但我们也无法通过 Apache Commons Email 1.4 版本访问 java.mail 配置,并且找不到解决方案。 我检查了他们的文档https://commons.apache.org/proper/commons-email/javadocs/api-1.4/index.html
没运气。 似乎附件 DataSource 只允许我获取内容和内容类型和名称,但如果它是内联附件/图像或像 Mime Parts 这样的常规附件,则不能。
我的印象是没有进入较低级别的解决方法......但我还没有检查所有附件类型 - 仅使用图像。 像这样的东西:
for(DataSource ds : mimeMessageParser.getAttachmentList()) {
for(String id : mimeMessageParser.getContentIds()) {
if(ds == mimeMessageParser.findAttachmentByCid(id)) {
// It is inline attachment with Content ID
break;
}
}
// If not found - it is file attachment without content ID
}
答案是 Apache Commons Email 做不到这样的事情。 您必须在 JDK 中进行较低级别的编码,并对老式的 MimeMessage 和 MultiPart 类进行编码,以便进行这些区分。
所以从 mimeMessageParser.getAttachmentList(); 打电话给我们现在有
if (mimeMessageParser.hasAttachments()) {
final Multipart mp = (Multipart) message.getContent();
if (mp != null) {
List<DataSource> attachments = extractAttachment(mp);
for (DataSource dataSource : attachments) {
saveAttachment(dataSource, subjectLineProperties, documentToUpload, firstHeaders);
}
}
}
private static List<DataSource> extractAttachment(Multipart multipart) {
List<DataSource> attachments = new ArrayList<>();
try {
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.getContent() instanceof Multipart) {
// part-within-a-part, do some recursion...
extractAttachment((Multipart) bodyPart.getContent());
}
System.out.println("bodyPart.getDisposition(): " + bodyPart.getDisposition());
if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
continue; // dealing with attachments only
}
InputStream is = bodyPart.getInputStream();
String fileName = bodyPart.getFileName();
String contentType = bodyPart.getContentType();
ByteArrayDataSource dataSource = new ByteArrayDataSource(is, contentType);
dataSource.setName(fileName);
attachments.add(dataSource);
}
} catch (IOException | MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return attachments;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.