如何在没有Gmail API

时间:2015-07-15 19:41:34

标签: gmail gmail-api

我想在一个没有原始邮件的帖子中收到回复邮件。但是,当我使用Users.messages:GET或Users.threads:GET时,我收到原始消息(不需要的)的回复(根据需要)。请参见下面的代码截图。

(据我所知,这个问题也提出了here,但是我没有发现提议的解决方案回答了问题,提出的解决方案的海报表明我开始提出一个新问题。尝试使用Users.threads,因为Tholle建议得到相同的结果。)

我是一个菜鸟,所以非常感谢任何帮助,如果我遗漏了一些明显的东西,我会道歉。

代码

var gapiGETRequest = function (gapiRequestURL)
  {
      var xmlHttp = new XMLHttpRequest();
      xmlHttp.open( "GET", gapiRequestURL, false );
      xmlHttp.send( null );
      return xmlHttp.responseText;
  }

var gapiRequestInboxMessagesAndToken = "https://www.googleapis.com/gmail/v1/users/me/messages?q=-label%3ASENT+in%3AINBOX&access_token=" + thisToken
var allMessagesReceived = gapiGETRequest(gapiRequestInboxMessagesAndToken)
var allMessagesObject = JSON.parse(allMessagesReceived)
var messageIdsOfReceivedMessages = [];
var getIdsOfReceivedMessages = function(responseObject){
  for(var i=0; i < responseObject.messages.length; i ++) {
    messageIdsOfReceivedMessages.push(responseObject.messages[i].id);
  }
}

var messageContentsArr = [];
var getMessageContents = function(messageIdList)
{
  for(var i=0; i < messageIdList.length; i++)
  {
    var gapiRequestMessageWithId = "https://www.googleapis.com/gmail/v1/users/me/messages/" + messageIdList[i] + "?access_token=" + thisToken
    var currentMessage = JSON.parse(gapiGETRequest(gapiRequestMessageWithId))
    var encodedMessageContents = currentMessage.payload.parts[0].body.data
    var decodedMessageContents = atob(encodedMessageContents.replace(/-/g, '+').replace(/_/g, '/'));
    messageContentsArr.push(decodedMessageContents)
  }
}

getIdsOfReceivedMessages(allMessagesObject);
getMessageContents(messageIdsOfReceivedMessages);

响应

result

2 个答案:

答案 0 :(得分:4)

您将收到完整的回复消息。当报告回复时,他们引用了原始消息,并且原始文本在回复消息中。你可能只想做Gmail和许多其他现代电子邮件应用程序所做的事情,并折叠/隐藏任何以&gt;开头的回复文本。

答案 1 :(得分:0)

这是我的解决方案。它有点长,但是我试图尽可能详细地记录下来。

Gmail API返回的句柄messagehttps://developers.google.com/gmail/api/v1/reference/users/messages#resource

输入:

Hello. This is my reply to message.

On Thu, Apr 30, 2020 at 8:29 PM John Doe <john.doe@example.com>
wrote:

> Hey. This is my message.
>


-- 
John Doe
My Awesome Signature

输出:

Hello. This is my reply to message.

代码:(不幸的是,该语法没有突出显示:P)

const message = await getMessageFromGmailApi();

const text = getGoogleMessageText(message);

console.log(text, '<= AWESOME RESULT');


function getGoogleMessageText(message) {
    let text = '';

    const fromEmail = getGoogleMessageEmailFromHeader('From', message);
    const toEmail = getGoogleMessageEmailFromHeader('To', message);

    let part;
    if (message.payload.parts) {
        part = message.payload.parts.find((part) => part.mimeType === 'text/plain');
    }

    let encodedText;
    if (message.payload.parts && part && part.body.data) {
        encodedText = part.body.data;
    } else if (message.payload.body.data) {
        encodedText = message.payload.body.data;
    }

    if (encodedText) {
        const buff = new Buffer(encodedText, 'base64');
        text = buff.toString('ascii');
    }

    // NOTE: We need to remove history of email.
    // History starts with line (example): 'On Thu, Apr 30, 2020 at 8:29 PM John Doe <john.doe@example.com> wrote:'
    //
    // We also don't know who wrote the last message in history, so we use the email that
    // we meet first: 'fromEmail' and 'toEmail'
    const fromEmailWithArrows = `<${fromEmail}>`;
    const toEmailWithArrows = `<${toEmail}>`;
    // NOTE: Check if email has history
    const isEmailWithHistory = (!!fromEmail && text.indexOf(fromEmailWithArrows) > -1) || (!!toEmail && text.indexOf(toEmailWithArrows) > -1);

    if (isEmailWithHistory) {
       // NOTE: First history email with arrows
       const historyEmailWithArrows = this.findFirstSubstring(fromEmailWithArrows, toEmailWithArrows, text);

       // NOTE: Remove everything after `<${fromEmail}>`
       text = text.substring(0, text.indexOf(historyEmailWithArrows) + historyEmailWithArrows.length);
       // NOTE: Remove line that contains `<${fromEmail}>`
       const fromRegExp = new RegExp(`^.*${historyEmailWithArrows}.*$`, 'mg');
       text = text.replace(fromRegExp, '');
    }

    text = text.trim()

    return text;
}


function getGoogleMessageEmailFromHeader(headerName, message) {
    const header = message.payload.headers.find((header) => header.name === headerName);

    if (!header) {
        return null;
    }

    const headerValue = header.value; // John Doe <john.doe@example.com>

    const email = headerValue.substring(
        headerValue.lastIndexOf('<') + 1,
        headerValue.lastIndexOf('>')
    );

    return email; // john.doe@example.com
}


function findFirstSubstring(a, b, str) {
    if (str.indexOf(a) === -1) return b;
    if (str.indexOf(b) === -1) return a;

    return (str.indexOf(a) < str.indexOf(b))
        ? a
        : b; // NOTE: (str.indexOf(b) < str.indexOf(a))
}