Node-imap, отображающий электронные письма - PullRequest
0 голосов
/ 30 апреля 2018

Я пытался правильно отображать электронные письма, но не смог этого сделать. Я только что отправил электронное письмо самому себе, и это выглядит так, когда я открываю его в hotmail enter image description here Но когда я открываю его в своем приложении с помощью node-imap, из «Отправленного» это выглядит так (обратите внимание на эти знаки '=' и еще какое-то странное дерьмо ..):

enter image description here

и это тот же вывод сообщений в консоли (по какой-то причине я получаю '=' в конце каждой строки и '3D' после каждого '='):

enter image description here

Теперь ... ЖЕ сообщение, тот же метод, только что открытое из папки "Входящие": http://prntscr.com/jbqtyw

просто обычный текст .. в консоли тоже: http://prntscr.com/jbquba

Я знаю его сложный вопрос, и его трудно понять, но я не могу упростить его. А вот код get (), который извлекает электронные письма:

get(id, params) {
    this.emailUsername = params.user.businessEmail;
    this.emailPassword = params.user.businessEmailPassword;
    this.host = params.user.serverIMAP;
    this.port = params.user.portIMAP;
    this.tls = params.user.serverSMTP;
    this.smtpPort = params.user.portSMTP;

    let currBox = params.query.box;
    let userEmail = this.emailUsername;

    return new Promise((resolve, reject) => {
      var imap = new Imap({
        user: this.emailUsername,
        password: this.emailPassword,
        host: this.host,
        port: this.port,
        tls: this.tls,
        tlsOptions: {
          rejectUnauthorized: false
        }
      });
      var response = {};

      function toUpper(thing) { return thing && thing.toUpperCase ? thing.toUpperCase() : thing; }

      function findAttachmentParts(struct, attachments) {
        attachments = attachments || []
        struct.forEach((i) => {
          if (Array.isArray(i)) findAttachmentParts(i, attachments)
          else if (i.disposition && ['INLINE', 'ATTACHMENT'].indexOf(toUpper(i.disposition.type)) > -1) {
            attachments.push(i)
          }
        })
        return attachments
      }

      function checkEmail(email) {
        return email.split('@')[1].split('.')[0];
      }

      function findTextPart(struct) {
        for (var i = 0, len = struct.length, r; i < len; ++i) {
          if (Array.isArray(struct[i])) {
            if (r = findTextPart(struct[i]))
              return r;
          } else if (struct[i].type === 'text'
            && struct[i].subtype === 'html') {
              return [struct[i].partID, struct[i].type + '/' + struct[i].subtype];
            } else if(struct[i].type === 'text'&& struct[i].subtype === 'plain') {
              return [struct[i].partID, struct[i].type + '/' + struct[i].subtype];
            }
        }
      }

      function getMsgByUID(uid, cb, partID) {
        var f = imap.seq.fetch(uid,
          (partID
            ? {
              bodies: [
                'HEADER.FIELDS (TO FROM SUBJECT DATE CC BCC)',
                partID[0]
              ]
            }
            : { struct: true })),
          hadErr = false;

        if (partID)
          var msg = { header: undefined, body: '', attrs: undefined };

        f.on('error', function (err) {
          hadErr = true;
          cb(err);
        });

        if (!partID) {
          f.on('message', function (m) {
            m.on('attributes', function (attrs) {
              partID = findTextPart(attrs.struct);
              const attachments = findAttachmentParts(attrs.struct);
              attachments.forEach((attachment) => {
                const filename = attachment.params.name  // need decode disposition.params['filename*'] !!!
                const encoding = toUpper(attachment.encoding)
                const f = imap.fetch(attrs.uid, { bodies: [attachment.partID] })
              })
            });
          });
          f.on('end', function () {
            if (hadErr)
              return;
            if (partID)
              getMsgByUID(uid, cb, partID);
            else
              cb(new Error('No text part found'));
          });
        } else {
          f.on('message', function (m) {
            m.on('body', function (stream, info) {
              var b = '';
              stream.on('data', function (d) {
                b += d;
              });
              stream.on('end', function () {
                if (/^header/i.test(info.which))
                  msg.header = Imap.parseHeader(b);
                else
                  msg.body = b;
                  console.log(b);
              });
            });
            m.on('attributes', function (attrs) {
              msg.attrs = attrs;
              msg.contentType = partID[1];
            });
          });
          f.on('end', function () {
            if (hadErr)
              return;
            cb(undefined, msg);
          });
        }
      }

      imap.once('ready', function () {
        imap.openBox(currBox, true, function (err, box) {
          if (err) throw err;
          getMsgByUID(id, function (err, msg) {
            if (err) throw err;
            response = msg;
            imap.end();
          });
        });
      });


      imap.once('error', function (err) {
        reject(err);
      });

      imap.once('end', function () {
        resolve(response);
      });

      imap.connect();
    })

  }

и во внешнем интерфейсе, просто отображая его как внутренний HTML:

<div class="content" [innerHtml]="bypassSecurity(email.body)">
    </div>

Итак, чтобы подвести итог ... один и тот же метод / вызов, получающий различный вывод из потока (один раз простой текст, один раз HTML-текст ... также в обоих случаях к сообщениям добавляется какое-то странное дерьмо, такое как '=' или '3D' на кажется как случайные места)? это правильный способ читать электронные письма?

1 Ответ

0 голосов
/ 30 апреля 2018

Это кодируемая кодировка для печати. ​​

Похоже, вам необходимо отменить кодировку передачи содержимого для разделов, которая обычно может быть Base64 или Quoted Printable.

...