mscdex / node-imap

An IMAP client module for node.js.
MIT License
2.16k stars 380 forks source link

There is not a single piece of code that explains how to get the message content #828

Closed bediu closed 3 years ago

bediu commented 3 years ago

This is a small rant

Every single issue that I've browsed here is telling me (and others) that I need to search for some ID in the message attributes then somehow search IMAP with that id and build the full contents. And I'm not even in the attachment part yet.

Seriously, we're not trying to fly space ships here, just give us chunks of code.

bediu commented 3 years ago

To those of you in the future with the same issue, use a library called mailparser because apparently getting mail contents is complex enough for a library.

I've found the following gist which helped: https://gist.github.com/bekce/2fedd3fdcd4a532169f9e3d193623a57

Import mailparser at the top of your file:

const simpleParser = require('mailparser').simpleParser;

After fetching messages with imap, you can use the mailparser library to parse the whole message body stream.

fetch.on('message', function(msg, seqno) {
    msg.on('body', function(stream, info) {

        simpleParser(stream, (err, mail) => { //use this

            mail.text //contains mail body/content in text form
            mail.headers.get('<header key>') //retreives header content by key (for example 'from' or 'to')

        });

    });
});

I will make another comment how to work with attachments and close the issue.

bediu commented 3 years ago

Regarding attachments, mailparser handles that too. If the message has attachments; the mail variable (from the code above) will then include an array of every attachment with the attachment buffer and meta data.

example:

attachments: [
    {
      type: 'attachment',
      content: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 0a>,
      contentType: 'text/plain',
      partId: '2',
      release: null,
      contentDisposition: 'attachment',
      filename: 'attachment-file.txt',
      headers: [Map],
      checksum: '6f5902ac237024bdd0c176cb93063dc4',
      size: 12
    }
  ]