Google Apps 脚本 GmailApp API 没有提供在您发送邮件时为邮件添加标签的方法,您可以通过 UI 执行此操作。这在问题跟踪器中显示为问题 1859,访问并加注星标以获取更新。
一种解决方法是利用线程 api。如果邮件被密送(bcc'd)给发件人,它也将作为新邮件出现在他们的收件箱中,我们可以在其中getInboxThreads()
找到它。将标签添加到此线程,并可选择将其标记为已读,然后将其存档。
代码也可用作要点。
/**
* An alternative to GmailApp.sendEmail(), which applies a
* label to the message thread in the sender's account.
*
* Sends an email message with optional arguments. The email can
* contain plain text or an HTML body. The size of the email
* (including headers, but excluding attachments) may not
* exceed 20KB.
*
* @param {String} recipient the addresses of the recipient
* @param {String} subject the subject line
* @param {String} body the body of the email
* @param {Object} options a JavaScript object that specifies
* advanced parameters, as documented
* for GmailApp.sendEmail()
* @param {String} label the label to be applied
*/
function sendAndLabel(recipient, subject, body, options, label) {
var sender = Session.getActiveUser().getEmail();
// Add sender to bcc list
if (options.bcc) {
options.bcc = options.bcc.split(',').concat(sender).join(',');
}
else {
options.bcc = sender;
}
GmailApp.sendEmail( recipient, subject, body, options )
// Check if label already exists, create if it doesn't
var newLabel = GmailApp.getUserLabelByName(label);
if (!newLabel) newLabel = GmailApp.createLabel(label);
// Look for our new message in inbox threads
Utilities.sleep(2000); // Wait for message to be received
var inboxThreads = GmailApp.getInboxThreads();
for (var t = 0; t < inboxThreads.length; t++) {
var foundSubject = inboxThreads[t].getFirstMessageSubject();
var numLabels = inboxThreads[t].getLabels().length; // Could add more criteria
if (foundSubject === subject && numLabels === 0) {
// Found our thread - label it
inboxThreads[t].addLabel(newLabel)
.markRead()
.moveToArchive();
break;
}
}
}
使用示例:
function test_sendAndLabel() {
var recipient = Session.getActiveUser().getEmail();
var subject = "Test Labelling";
var body = "This email is testing message labelling.";
// var options = {bcc:"someone@example.com"};
var options = {};
var label = "LabelTest";
sendAndLabel(recipient, subject, body, options, label);
}