Gmail API解码Javascript中的邮件

问题描述 投票:8回答:5

我在解码使用Gmail API收到的电子邮件的邮件正文时遇到严重问题。我想抓取消息内容并将内容放在div中。我正在使用base64解码器,我知道它不会解码编码不同的电子邮件,但我不知道如何检查电子邮件以决定使用哪个解码器 - 说明它们是utf-8编码的电子邮件已成功解码base64解码器,但不是utf-8解码器。

我已经研究了几天的电子邮件解码,而且我已经了解到我在这里的联盟有点不合适。我之前没有做过很多关于电子邮件编码的工作。这是我用于获取电子邮件的代码:

gapi.client.load('gmail', 'v1', function() {
var request = gapi.client.gmail.users.messages.list({
  labelIds: ['INBOX']
});
request.execute(function(resp) {
  document.getElementById('email-announcement').innerHTML = '<i>Hello! I am reading your <b>inbox</b> emails.</i><br><br>------<br>';
  var content = document.getElementById("message-list");
  if (resp.messages == null) {
    content.innerHTML = "<b>Your inbox is empty.</b>";
  } else {
    var encodings = 0;
    content.innerHTML = "";
    angular.forEach(resp.messages, function(message) {
      var email = gapi.client.gmail.users.messages.get({
      'id': message.id
      });
      email.execute(function(stuff) {
        if (stuff.payload == null) {
          console.log("Payload null: " + message.id);
        }
        var header = "";
        var sender = "";
        angular.forEach(stuff.payload.headers, function(item) {
          if (item.name == "Subject") {
            header = item.value;
          }
          if (item.name == "From") {
            sender = item.value;
          }
        })
        try {
          var contents = "";
          if (stuff.payload.parts == null) {
            contents = base64.decode(stuff.payload.body.data);
          } else {
            contents = base64.decode(stuff.payload.parts[0].body.data);
          }
          content.innerHTML += '<b>Subject: ' + header + '</b><br>';
          content.innerHTML += '<b>From: ' + sender + '</b><br>';
          content.innerHTML += contents + "<br><br>";
        } catch (err) {
          console.log("Encoding error: " + encodings++);
        }
      })
    })
  }
 });
});

我正在执行一些检查和调试,因此有剩余的console.log和其他一些仅用于测试的东西。不过,你可以在这里看到我想要做的事情。

解码我从Gmail API中提取的电子邮件的最佳方法是什么?我应该尝试将电子邮件放入<script>,其中charsettype属性与电子邮件的编码内容相匹配吗?我相信我记得charset只适用于src属性,我不会在这里。有什么建议?

javascript email character-encoding decoding gmail-api
5个回答
16
投票

对于我正在编写的原型应用程序,以下代码对我有用:

var base64 = require('js-base64').Base64;
// js-base64 is working fine for me.

var bodyData = message.payload.body.data;
// Simplified code: you'd need to check for multipart.

base64.decode(bodyData.replace(/-/g, '+').replace(/_/g, '/'));
// If you're going to use a different library other than js-base64,
// you may need to replace some characters before passing it to the decoder.

注意:这些要点没有明确记录,可能是错误的:

  1. users.messages: get API默认返回“已解析的正文内容”。无论Content-TypeContent-Transfer-Encoding标头如何,此数据似乎始终以UTF-8和Base64编码。 例如,我的代码解析带有这些标题的电子邮件没有问题:Content-Type: text/plain; charset=ISO-2022-JPContent-Transfer-Encoding: 7bit
  2. Base64编码varies among various implementations的映射表。 Gmail API使用-_作为表格的最后两个字符,由RFC 4648的“URL和文件名安全字母”1定义。 检查Base64库是否使用不同的映射表。如果是这样,请在将正文传递给解码器之前将这些字符替换为您的库所接受的字符。

1文档中有一条支持线:the "raw" format返回“body content as base64url encoded string”。 (谢谢埃里克!)


3
投票

使用atob解码JavaScript中的消息(请参阅ref)。要访问消息有效负载,可以编写一个函数:

var extractField = function(json, fieldName) {
  return json.payload.headers.filter(function(header) {
    return header.name === fieldName;
  })[0].value;
};
var date = extractField(response, "Date");
var subject = extractField(response, "Subject");

引用自我以前的SO Question

var part = message.parts.filter(function(part) {
  return part.mimeType == 'text/html';
});
var html = atob(part.body.data);

如果上述内容无法100%正确解码,@ cgenco对以下答案的评论可能适用于您。在那种情况下,做

var html = atob(part.body.data.replace(/-/g, '+').replace(/_/g, '/'));

2
投票

以下是解决方案:Gmail API - “Users.messages:get”方法响应message.payload.body.data分区base64数据,它用“ - ”符号分隔。它不是完整的base64编码文本,它是base64文本的一部分。你必须尝试解码它的每一部分或通过联合制作一个单声道字符串并替换“ - ”符号。在此之后,您可以轻松地将其解码为人类文本。你可以在这里手动检查每个部分https://www.base64decode.org


1
投票

请使用网络安全解码器解码Gmail电子邮件和附件。当我使用base64decoder时,我得到了空白页,不得不使用:https://www.npmjs.com/package/urlsafe-base64


0
投票

我可以使用https://simplycalc.com/base64-decode.php上的其他工具轻松解码

在JS:https://www.npmjs.com/package/base64url

在Python 3中:

import base64
base64.urlsafe_b64decode(coded_string)
© www.soinside.com 2019 - 2024. All rights reserved.