Problems with Spanish Characters (á, é, í, ó, ú, ñ

2019-09-18 19:27发布

问题:

I need your help. Maybe it's a very simple error, but I can't solve it. This code works great in order to create a Gmail draft. But I have problems with the Spanish characters: á, é, í, ó, ú , ñ in the subject. The HTML Body works fine, it recognizes these characters (á, é, í, ó, ú, ñ).

I believe that I need to put the code "charset=UTF-8" in a some special side. What do you recommend?

function createHTMLDraftInGmail() {

 var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope
 var htmlBody = "<p>Hello, I am an HTML message</p><hr>";
 var raw = 'From: Me <amit@labnol.org>\r\n' +
        'To: You <hello@example.com.com>\r\n' +
        'Subject: Save Draft Message\r\n' +
        'Content-Type: text/html; charset=UTF-8\r\n' + 
        '\r\n' + htmlBody;

var draftBody = 
Utilities.base64Encode(raw,Utilities.Charset.UTF_8).replace(/\//g,'_').replace(/\+/g,'-');

var params = {
method      : "post",
contentType : "application/json",
headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
payload:JSON.stringify({
  "message": {
    "raw": draftBody
  }
})
};

var resp =
  UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/me/drafts", params);
 Logger.log(resp.getContentText());
 }

Greetings,

回答1:

I made some test and found that when you send an email with those characters, it adds the following to the subject line:

=?ISO-8859-1?Q?  ?=

The =? indicates the start and ?= the end of the line. The ISO-8859-1? makes reference to the charset. I'm not sure about the Q?.

Between the Q? and ?= you will have your subject message. All the spanish characters will have to be encoded, eg. 'El Niño' (the kid), would have to be written as: 'El Ni=F1o'. Where =F1 corresponds to the 'ñ' in the ISO-8859-1 charset.

Investigating a little bit more, I also found that you can encode the subject string in base64 and add the following line to the Subject line:

=?UTF-8?B?RWwgTmnDsW8=?=

In this case RWwgTmnDsW8= is the string encoded of 'El Niño'.

This second approach is easier than the first one (I found it after writing the first part), try it and see if it works for you.