Kerim092
Kerim092

Reputation: 1497

Node-imap append new email to drafts

Been using node-imap , I'm trying to save emails to drafts, it looks like this:

        var imap = new Imap({
          user: this.emailUsername,
          password: this.emailPassword,
          host: this.host,
          port: this.port,
          tls: this.tls,
          debug: console.log
        });

        imap.once('ready', function () {
          imap.openBox('inbox.Drafts', false, (err, box) => {
            if (err) throw err;
            let str = "to:" + data.to + " subject:" + data.subject + " body: " + data.body + " text: " + data.body;

            imap.append(str);
          })
        });`

This code makes new draft email but seems I cant append data to its fields... It says only strings, buffer or arraybuffer can be passed into imap.append() as data. So I tried to pass JSON.stringify(data) - nothing gets appended. When I pass it like string as Its shown in code above, only 'to' value gets appended into 'to' field.. If i modify string like this:

     let str = "to:" + data.to + ", subject:" + data.subject + ", body: " + data.body + ", text: " + data.body;
  //or 
     let str = "to:" + data.to + "; subject:" + data.subject + "; body: " + data.body + "; text: " + data.body;

All data gets appended but all of it into 'to' field like:

[email protected], some subject, some body-text

What is the form of the string that should be passed into function? Am I doing something wrong? Why is imap.append(JSON.stringify(data)) not working?

Upvotes: 2

Views: 1623

Answers (1)

Kerim092
Kerim092

Reputation: 1497

Thanks to @Max for the help, It required a mime message type... I solved it by installing mimemessage module and used its docs. My working code looks like this:

        var mimemessage = require('mimemessage');

        let msg, htmlEntity, plainEntity;

        msg = mimemessage.factory({
          contentType: 'multipart/alternate',
          body: []
        });
        htmlEntity = mimemessage.factory({
          contentType: 'text/html;charset=utf-8',
          body: data.body
        });
        plainEntity = mimemessage.factory({
          body: data.body
        });
        msg.header('Message-ID', '<1234qwerty>');
        msg.header('To', data.to);
        msg.header('Subject', data.subject);
        //msg.body.push(htmlEntity);
        msg.body.push(plainEntity);

        imap.append(msg.toString());

Upvotes: 2

Related Questions