您可以使用GMail API来执行此操作。您需要为您的项目启用 API。在编辑器中,选择Resources > Advanced Google services
,然后单击“这些服务也必须在Google Developers Console 中启用”。在那里,启用 GMail API。
修改消息
使用示例:
modifyMessage('me', messageId, ['stack','overflow']); // add two labels
modifyMessage('me', messageId, null, ['stack','overflow']); // remove two labels
TL;DR完整代码在这个 gist 中可用,在下面的隐藏代码片段中可用。
/**
* Modify the Labels a Message is associated with.
* Throws if unsuccessful.
* see https://developers.google.com/gmail/api/v1/reference/users/messages/modify
*
* @param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* @param {String} messageId ID of Message to modify.
* @param {String[]} labelsToAdd Array of Label names to add.
* @param {String[]} labelsToRemove Array of Label names to remove.
*
* @returns {Object} Users.messages resource, see reference.
*/
function modifyMessage(userId, messageId, labelsToAdd, labelsToRemove) {
labelsToAdd = labelsToAdd || [];
labelsToRemove = labelsToRemove || [];
// see https://developers.google.com/gmail/api/v1/reference/users/messages/modify
var url = 'https://www.googleapis.com/gmail/v1/users/${userId}/messages/${id}/modify'
.replace("${userId}","me")
.replace("${id}", messageId );
var headers = {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
};
var addLabelIds = [];
for (var i=0; i<labelsToAdd.length; i++) {
addLabelIds[i] = getLabelId( labelsToAdd[i] );
}
var removeLabelIds = [];
for (var i=0; i<labelsToRemove.length; i++) {
removeLabelIds[i] = getLabelId( labelsToRemove[i], false );
}
var request = {
'addLabelIds': addLabelIds,
'removeLabelIds': removeLabelIds
};
var params = {
method: "post",
contentType: "application/json",
headers: headers,
payload: JSON.stringify(request),
muteHttpExceptions: true
};
//var check = UrlFetchApp.getRequest(url, params); // for debugging
var response = UrlFetchApp.fetch(url, params);
var result = response.getResponseCode();
if (result == '200') { // OK
return JSON.parse(response.getContentText());
}
else {
// This is only needed when muteHttpExceptions == true
var err = JSON.parse(response.getContentText());
throw new Error( 'Error (' + result + ") " + err.error.message );
}
}
/**
* Get the Label ID for the given LabelName. If Label isn't found, it will be created
* depending on the state of ok2Create.
* Throws if unsuccessful.
* See https://developers.google.com/gmail/api/v1/reference/users/messages/modify.
*
* @param {String} labelName Name of label to retrieve ID for.
* @param {Boolean} ok2Create (optional) Set true if a label should be created when not found.
* Default is true.
*
* @returns {String} ID of Label, or null if not found or created.
*/
function getLabelId( labelName, ok2Create ) {
if (typeof ok2Create == 'undefined') ok2Create = true;
var id = null;
// see https://developers.google.com/gmail/api/v1/reference/users/labels/list
var url = 'https://www.googleapis.com/gmail/v1/users/${userId}/labels'
.replace("${userId}","me") // The user's email address. The special value me can be used to indicate the authenticated user.
var headers = {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
};
var params = {
method: "get",
contentType: "application/json",
headers: headers,
muteHttpExceptions: true
};
//var check = UrlFetchApp.getRequest(url, params); // for debugging
var response = UrlFetchApp.fetch(url, params);
var result = response.getResponseCode();
if (result == '200') { // OK
var labels = JSON.parse(response.getContentText()).labels;
var found = false;
for (var i=0; i<labels.length & !found; i++) {
if (labels[i].name == labelName) {
found = true;
id = labels[i].id;
}
}
if (!found && ok2Create) {
id = createLabel( labelName );
}
return id;
}
else {
// This is only needed when muteHttpExceptions == true
var err = JSON.parse(response.getContentText());
throw new Error( 'Error (' + result + ") " + err.error.message );
}
}
/**
* Create Label for given `labelName`.
* Throws if unsuccessful.
* See https://developers.google.com/gmail/api/v1/reference/users/messages/modify.
*
* @param {String} labelName Name of label to create
*
* @returns {String} ID of Label.
*/
function createLabel( labelName ) {
var id = null;
// see https://developers.google.com/gmail/api/v1/reference/users/labels/create
var url = 'https://www.googleapis.com/gmail/v1/users/${userId}/labels'
.replace("${userId}","me") // The user's email address. The special value me can be used to indicate the authenticated user.
var headers = {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
};
var request = {
'name': labelName
};
var params = {
method: "post",
contentType: "application/json",
headers: headers,
payload: JSON.stringify(request),
muteHttpExceptions: true
};
//var check = UrlFetchApp.getRequest(url, params); // for debugging
var response = UrlFetchApp.fetch(url, params);
var result = response.getResponseCode();
if (result == '200') { // OK
var label = JSON.parse(response.getContentText());
id = label.id;
return id;
}
else {
// This is only needed when muteHttpExceptions == true
var err = JSON.parse(response.getContentText());
throw new Error( 'Error (' + result + ") " + err.error.message );
}
}
/**
* Modify the Labels a Message is associated with.
* Throws if unsuccessful.
* see https://developers.google.com/gmail/api/v1/reference/users/messages/modify
*
* @param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* @param {String} messageId ID of Message to modify.
* @param {String[]} labelsToAdd Array of Label names to add.
* @param {String[]} labelsToRemove Array of Label names to remove.
*
* @returns {Object} Users.messages resource, see reference.
*/
function modifyMessage(userId, messageId, labelsToAdd, labelsToRemove) {
labelsToAdd = labelsToAdd || [];
labelsToRemove = labelsToRemove || [];
// see https://developers.google.com/gmail/api/v1/reference/users/messages/modify
var url = 'https://www.googleapis.com/gmail/v1/users/${userId}/messages/${id}/modify'
.replace("${userId}","me")
.replace("${id}", messageId );
GMail API 是一种 RESTful API,与使用内置 GMailApp 服务相比,它可以更灵活、更详细地访问线程、消息、标签、草稿和历史记录。在我们的脚本中,我们通过 URL 访问 API - 在这里,我们首先在modify
Message 方法的基本 URL 中填写详细信息。
var headers = {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
};
除了为我们的项目启用 API 之外,每个请求都需要用户身份验证,这是通过在命令头中嵌入一个Bearer Token来完成的。
接下来,我们将构建其余的命令参数。
var addLabelIds = [];
for (var i=0; i<labelsToAdd.length; i++) {
addLabelIds[i] = getLabelId( labelsToAdd[i] );
}
var removeLabelIds = [];
for (i=0; i<labelsToRemove.length; i++) {
removeLabelIds[i] = getLabelId( labelsToRemove[i], false );
}
var request = {
'addLabelIds': addLabelIds,
'removeLabelIds': removeLabelIds
};
操作modify
调用规范,POST
有效负载包含标签 ID 列表。这些 ID 无法通过内置 GMail 服务获得,因此我们还将为此使用 GMail API - 这getLabelId()
是另一个与此类似的功能,专门用于按名称检索标签 ID,并根据需要创建新标签。请参阅该代码的要点或片段。
var params = {
method: "post",
contentType: "application/json",
headers: headers,
payload: JSON.stringify(request),
muteHttpExceptions: true
};
//var check = UrlFetchApp.getRequest(url, params); // for debugging
var response = UrlFetchApp.fetch(url, params);
最后,我们params
为命令组装了对象,其属性包含headers
我们的身份验证令牌和payload
命令参数,stringify
-d 用于传输。muteHttpExceptions: true
在失败的情况下设置静噪系统生成的异常,以便我们可以自己处理它们。
我已经注释掉了一个调用UrlFetchApp.getRequest()
- 在发送命令之前验证命令的内容非常方便。
调用将UrlFetchApp.fetch()
我们的命令传输到在我们建立的 URL 上运行的服务。
var result = response.getResponseCode();
if (result == '200') { // OK
return JSON.parse(response.getContentText());
}
当收到响应时,我们首先检查result
命令的 ,它是HTTP 状态代码的形式。A200 OK
告诉我们我们成功了,所以我们继续从响应中提取我们的结果。JSON.parse()
将消息中的JSON 字符串转换为 JavaScript 对象,我们将其返回给调用者。
else {
// This is only needed when muteHttpExceptions == true
var err = JSON.parse(response.getContentText());
throw new Error( 'Error (' + result + ") " + err.error.message );
}
}
但是,如果我们遇到错误,我们会抛出自己的异常。根据命令的详细信息,我们可能希望以不同方式处理特定错误。例如,在这个modify
命令中,如果我们提供一个不存在的标签 ID,我们将收到一个错误:
错误:错误(400)无效标签:“无效标签”