HiraokaHyperTools / msgreader

40 stars 9 forks source link

Cannot parse MSG with EML attachments #6

Closed markb-trustifi closed 4 years ago

markb-trustifi commented 4 years ago

For example, this file cannot be parsed: Undeliverable NDR with graph protection2.zip

let msgfile = fs.readFileSync('Undeliverable NDR with graph protection2.msg');
let testMsg = new MsgReader(msgfile);
let testMsgInfo = testMsg.getFileData();
testMsgInfo.attachments.forEach(att => {
   att.content = testMsg.getAttachment(att);
   att.content = att.content && att.content.content && Buffer.from(att.content.content);
});
kenjiuno commented 4 years ago

Thanks. 1.3.0 will have msg in msg support.

This listAttachmentsRecursively utility function will help to flatten attachment files included in msg in msg.

function listAttachmentsRecursively(fieldsData, delimiter) {
  const attachments = []

  const walk = (fieldsData, prefix, attachments) => {
    for (const att of fieldsData.attachments) {
      if (att.innerMsgContent) {
        walk(att.innerMsgContentFields, att.name + delimiter, attachments);
      }
      else {
        attachments.push({
          fileName: prefix + att.fileName,
          attachmentRef: att,
        })
      }
    }
  }

  walk(fieldsData, "", attachments)

  return attachments
}
    const msgFileBuffer = fs.readFileSync(msgFilePath)
    const testMsg = new MsgReader(msgFileBuffer)
    const testMsgInfo = testMsg.getFileData()

    fs.mkdirSync(path.resolve(saveToDir), { recursive: true })

    const attachments = listAttachmentsRecursively(testMsgInfo, "_");
    for (let attachment of attachments) {
      const attFilePath = path.resolve(saveToDir, attachment.fileName);
      fs.writeFileSync(attFilePath, testMsg.getAttachment(attachment.attachmentRef).content)
    }
H:\Proj\msgreader>node cli list-att test/msgInMsgInMsg.msg
I have attachments!_green.png
blue.png
kenjiuno commented 4 years ago

https://www.npmjs.com/package/@kenjiuno/msgreader/v/1.3.0

markb-trustifi commented 4 years ago

Thank you for update. It is working now!