Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Gmail API-如何正确解析邮件正文数据?_Ruby On Rails_Encoding_Utf 8_Gmail_Ascii - Fatal编程技术网

Ruby on rails Gmail API-如何正确解析邮件正文数据?

Ruby on rails Gmail API-如何正确解析邮件正文数据?,ruby-on-rails,encoding,utf-8,gmail,ascii,Ruby On Rails,Encoding,Utf 8,Gmail,Ascii,我使用的是新的Gmail API,我完全专注于如何正确处理Ruby/Rails中文本/普通消息和文本/html消息的[body][data]部分的编码 假设数据=编码的消息部分 在其上调用Base64.decode64(data).unpack(“M”),将返回一个US-ASCII编码的文本体,其中包含网页上显示的大量缺失字符 调用Base64.decode64(data).encode('UTF-8')会引发从US-ASCII到UTF-8的转换错误 然而,如果我使用Base64.decode6

我使用的是新的Gmail API,我完全专注于如何正确处理Ruby/Rails中文本/普通消息和文本/html消息的[body][data]部分的编码

假设数据=编码的消息部分

在其上调用
Base64.decode64(data).unpack(“M”)
,将返回一个US-ASCII编码的文本体,其中包含网页上显示的大量缺失字符

调用
Base64.decode64(data).encode('UTF-8')
会引发从US-ASCII到UTF-8的转换错误

然而,如果我使用
Base64.decode64(data.encode('UTF-8',{:invalid=>:replace,:unde=>:replace,:replace=>'?})
,我仍然会看到很多问号

有人能告诉我如何正确编码消息体并以UTF-8显示吗

电子邮件JSON响应的格式如下所示:

"parts": [
   {
    "partId": "0",
    "mimeType": "text/plain",
    "filename": "",
    "headers": [
     {
      "name": "Content-Type",
      "value": "text/plain; charset=UTF-8"
     },
     {
      "name": "Content-Transfer-Encoding",
      "value": "quoted-printable"

使用
Base64.urlsafe\u decode64
对消息正文进行解码

var base64toUTF8 = function base64toUTF8(str,urlsafe) {
  if(urlsafe) {
    str = str.replace(/_/g,"/");
    str = str.replace(/-/g,"+");
  }
  if(typeof window) {
    return decodeURIComponent(escape(window.atob( str )));
  }
  else if(typeof module !== 'undefined' && module.exports) {
    return new Buffer("SGVsbG8gV29ybGQ=", 'base64').toString('utf8');
  }
};

仅需将base64编码的字符“-”替换为“+”,将“”替换为“/”

根据Bhargav Krishna的回答,这里有一个nodeJS友好的版本:

var base64toUTF8 = function base64toUTF8(str, urlsafe) {
  if (urlsafe) {
    str = str.replace(/_/g,"/");
    str = str.replace(/-/g,"+");
  }
  return new Buffer(str, 'base64').toString('utf8');
};
我删除了对windowvsmodule的引用,并使其成为nodejsone实际使用的
str
,而不仅仅是“helloworld!”