Currently we receive an email which gets parsed by
MimeMessageParser mimeMessageParser = parse(message);
and later pull out the attachments with
if (mimeMessageParser.hasAttachments()) {
List<DataSource> attachments = mimeMessageParser.getAttachmentList();
for (DataSource dataSource : attachments) {
saveAttachment(dataSource, subjectLineProperties, documentToUpload, firstHeaders);
}
}
The issue is that getAttachmentList is also returning inline images like in the signature line the business logo, and we do not want to pull out the inline images as attachments. We just want the actual email attachments. ATTACHMENT versus INLINE, but we also have no access to java.mail disposition via the Apache Commons Email 1.4 version, and can't find a solution. I checked their documentation https://commons.apache.org/proper/commons-email/javadocs/api-1.4/index.html
No luck. It seems that the attachments DataSource only allows me to get content and content type and name, but not if it is an inline attachment/image or a regular attachment like Mime Parts can.
The answer is that Apache Commons Email cannot do such a thing. You have to go lower level and code the old fashioned MimeMessage and MultiPart classes within the JDK in order to make these distinctions.
So from mimeMessageParser.getAttachmentList(); call we now have
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;
}