Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

node.js - GMail API Replying to Email Thread Using NodeJS

Dear All: I am sure many of you have discussed above topic multiple times after I am going through all the example and references I have managed to write the code to reply to same email ThreadID. But Unfortunately while I am responding to same ThreadID emails it's going as new email. I have attached my complete NodeJS Code help me to review and let me know where should I have to make the changes.

const {google} = require('googleapis');
const mailComposer = require('nodemailer/lib/mail-composer');
var program_name = process.argv[0]; //value will be "node"
var script_path = process.argv[1]; //value will be "yourscript.js"
var Sender_Email = process.argv[2]; //value will be "Sender Email"
var Receiver_Email = process.argv[3]; //value will be "Email To"
//var CC_Email = process.argv[4]; //value will be "Email Cc"
var Email_Subject = process.argv[4]; //value will be "Email Subject"
var Email_Template = process.argv[5]; //value will be "Email Template"
var ThreadID = process.argv[6]; //Path to attach the file
var Dec_Message_ID = process.argv[7]; //Encoded messageid
var FileAttachment = process.argv[8]; //Path to attach the file
var dateFormat = require('dateformat');
var day=dateFormat(new Date(), "mmm dd, yyyy HH:MM tt");
class CreateMail{

    constructor(auth, to, cc, sub, body, task, attachmentSrc = [FileAttachment]){

        this.me = Sender_Email;
        this.task = task;
        this.auth = auth;
        this.to = Receiver_Email;
        //this.cc = CC_Email;
        this.sub = Email_Subject;       
        var fs = require('fs');
        this.body = fs.readFileSync(Email_Template,{encoding:'utf-8'});     
        
        this.gmail = google.gmail({version: 'v1', auth});
        this.attachment = attachmentSrc;
    }

    //Creates the mail body and encodes it to base64 format.
    makeBody(){
        if(this.attachment.length>0){
        var arr = [];
        for(var i=0;i<this.attachment.length;i++){
            arr[i] = {
                path: this.attachment[i],
                encoding: 'base64'
            }
        }
        }
        let mail;
        //Mail Body is created.
        if(this.attachment.length>0){
            mail = new mailComposer({
                
                from: "Arthanareeswaran Chandrasekaran <[email protected]>",                            
                //sender: this.me,
                to: this.to,                
                //cc: this.cc,
                replyTo: this.to,
                
                inReplyTo: "<CAO29sXBTxmE8M=xyTkdFfsrxB_Mdr5e6N6vXiijwTY9rn1kzpQ@mail.gmail.com>",
                references: "<CAF7UyHwMrUvy-ZLNyRfjDmX876EKi5T-oc8E_tXy2PwO19dZ_Q@mail.gmail.com> <CAO29sXBH_B0yG4G2p6tdW1uk_tq9qFXmc01CPO5HJopkvMbU4Q@mail.gmail.com> <CAO29sXCcHv4LQSumjht_5zHEYvSzjfYkGr+yCEHfjwnqRvt0=Q@mail.gmail.com> <CAO29sXCPAxzWG0dC-TKEi4cR3xM8hbHhSJQ0ZAhbXBjsp503oA@mail.gmail.com> <CAO29sXA2mpqx6qbEeB5ke_6kUTrwXsqMD8ku0Aq3E_R07YzCLg@mail.gmail.com> <CAO29sXBTxmE8M=xyTkdFfsrxB_Mdr5e6N6vXiijwTY9rn1kzpQ@mail.gmail.com>",
                
                            
                subject: this.sub,  
                html: this.body,
                
                textEncoding: "base64",
                attachments: arr
                
            }); 
        }
        else{
            mail = new mailComposer({
                
                to: this.to,                
                cc: this.cc,
                html: this.body,
                subject: this.sub,              
                textEncoding: "base64"              
                
            });
        }
        
        //Compiles and encodes the mail.
        mail.compile().build((err, msg) => {
            if (err){
                return console.log('Error compiling email ' + error);
            } 
        
            const encodedMessage = Buffer.from(msg)
              .toString('base64')             
              .replace(/+/g, '-')
              .replace(///g, '_')            
              .replace(/=+$/, '');
            
            if(this.task === 'mail'){
                this.sendMail(encodedMessage);
            }
            else{
                this.saveDraft(encodedMessage);
            }
        });
    }

    //Send the message to specified receiver.
        sendMail(encodedMessage){
        this.gmail.users.messages.send({
            userId: this.me,
            resource: {
                                                                                
                raw: encodedMessage,                                
                threadId: ThreadID

            }

        }, (err, result) => {
            if(err){
                return console.log('GMail API - The API returned an error: ' + err);
            }

            console.log("GMail API Sending Email Reply from server:", result.data);
        });
        }

    //Saves the draft.
        saveDraft(encodedMessage){
        this.gmail.users.drafts.create({
            'userId': this.me,
            'resource': {
              'message': {
                'raw': encodedMessage,
                threadId: ThreadID
              }
            }
        })
        }

    //Deletes the draft.
        deleteDraft(id){
        this.attachment.gmail.users.drafts.delete({
            id: id,
            userId: this.me
        });
        }

        }

module.exports = CreateMail;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like the issue here is the fact that you turned off the Conversation view setting from Gmail.

According to the documentation:

You can choose whether replies to emails are grouped in conversations, or if each email shows up in your inbox separately.

Hence, if this setting is not turned on, the email will show up separately in your inbox.

Reference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...