如何使用imap NodeJs将电子邮件正文和附件放在一个JSON对象中

xxhby3vn  于 2022-12-29  发布在  Node.js
关注(0)|答案(1)|浏览(240)

我喜欢在JSON对象中存储电子邮件正文,如[日期、主题、收件人、发件人、附件],但我找不到一个不使用msg.once('attributes',...)就能获取附件的解决方案。
我不需要下载附件,我只需要将编码后的BASE64附件放入JSON对象中。

    • 我的密码:**
var mail = {
  date: "",
  Subject: "",
  Sender: "",
  Receiver: "",
  Attachment: null
}

imap.once('ready', function() {
      imap.openBox('INBOX', true, function(err, box) {
        if (err) throw err;
        var f = imap.seq.fetch('1:3', {
          bodies: ['HEADER.FIELDS (FROM TO SUBJECT DATE)'],
          struct: true
        });
        f.on('message', function(msg, seqno) {
          simpleParser(stream).then(parsed => {
            var mail = {
              date: parsed.date,
              Subject: parsed.subject,
              Sender: parsed.from.value,
              Receiver: parsed.to.value,
              Attachment: null //i don't know how to get the attachment
              it always says attachment = [] when i console log parsed

            }
          })
        });
        msg.once('attributes', function(attrs) {
            var attachments = findAttachmentParts(attrs.struct);
            console.log(prefix + 'Has attachments: %d', attachments.length);
            for (var i = 0, len = attachments.length; i < len; ++i) {
              var attachment = attachments[i];
            },
            language: null
          }
          */
          console.log(prefix + 'Fetching attachment %s', attachment.params.name);
          var f = imap.fetch(attrs.uid, { //do not use imap.seq.fetch here
            bodies: [attachment.partID],
            struct: true
          });
          //build function to process attachment message
          f.on('message', buildAttMessageFunction(attachment));
        }
      });
w8f9ii69

w8f9ii691#

我通过使用promises和simpleparser解决了这个问题:

imap.search([['X-GM-RAW', 'has:attachment in:unread'], ['SINCE', new Date()], ], (err, results) = >{
    const f = imap.fetch(results, {
        bodies: ''
    });
    f.on('message', (msg) = >{
        const attributesPromise = new Promise((resolve) = >{
            msg.on('attributes', (attrs) = >{
                resolve(attrs);
            });
        });
        const bodyPromise = new Promise((resolve) = >{
            msg.on('body', async(stream) = >{
                const parsed = await simpleParser(stream);
                resolve(parsed);
            });
        });
        Promise.all([attributesPromise, bodyPromise]).then((data) = >{
            const[attributes, emailContent] = data;
            console.log(attributes, emailContent);
        });
    });
    f.once('error', (ex) = >{
        return Promise.reject(ex);
    });
    f.once('end', () = >{
        console.log('Done fetching all messages!');
        imap.end();
    });
});

编辑:我刚刚看到你只需要在一个请求中包含正文和附件。这已经在下面的parsed变量中完成了。然而,下面的答案一次就给了你属性和emailContent。这可以用来进一步更新基于内容的电子邮件。例如,如果电子邮件的主题包含一些内容,则通过uid设置标签。

相关问题