2014-11-05 114 views

回答

3

首先,由於您要向剛剛發送的線索添加標籤,因此您必須使用GmailApp。 MailApp只允許您發送郵件,而不是與用戶的收件箱交互。

正如您所見,GmailApp.sendEmail()不返回消息或線程ID。在這種情況下,您可以搜索剛剛發送的線索,但是您必須考慮何時向此人發送了幾條消息。

只要您不是很快發送重複郵件,就可以依靠調用GmailApp.search()將以與Web UI相同的順序返回線程。因此,搜索'from:me到:[email protected]'可能會返回多個線程,但第一個結果將成爲最近發送的消息的線程。

我們一個郵件發送到一個名爲Recipients一堆的選項卡中列出地址的玩具例子:

var recipients = SpreadsheetApp.getActiveSpreadsheet() 
           .getSheetByName('Recipients') 
           .getDataRange() 
           .getValues(); 
recipients.shift(); // Only if the Recipients sheet contained a header you need to remove 
var d = new Date(); 
var dateText = d.toLocaleString(); // Pretty-printed timestamp 
var newLabel = GmailApp.createLabel(dateText); // Label corresponding to when we ran this 
for (var i = 0; i < recipients.length; i++) { 
    GmailApp.sendEmail(recipients[i], 'This is a test', 'Of the emergency broadcast system'); 
    var sentThreads = GmailApp.search('from:me to:' + recipients[i]); 
    var mostRecentThread = sentThreads[0]; 
    mostRecentThread.addLabel(newLabel); 
} 
1

Google Apps腳本將不會返回線程ID但是在發送電子郵件後,你可以做的是搜索您的郵箱主體和標籤應用到結果的第一個線程。

var to="[email protected]", subject="email subject"; 
GmailApp.sendEmail(to,subject,msg_to_bd); 
var threads = GmailApp.search("to:" + to + " in:sent subject:" + subject, 0, 1); 
threads[0].addLabel(label); 
1

由於所有的GmailApp.send *方法(在寫作的時間)不返回消息或線程標識符,並且由於GmailMessage對象沒有send *方法,因此最安全的做法似乎是在發送消息時在消息中嵌入唯一標識符。然後搜索包含唯一標識符的電子郵件。

此代碼適用於我作爲實驗。請注意,爲了搜索成功,我必須睡眠()幾秒鐘。

function tryit() { 
    var searchTerm = Utilities.getUuid(); 
    GmailApp.sendEmail('[email protected]', 'oh please', 
         'custom id: ' + searchTerm); 
    Utilities.sleep(2000); 
    var threadIds = GmailApp.search(searchTerm); 
    Logger.log(threadIds); 
    if (threadIds.length != 1) { 
     Browser.msgBox('Found too many threads with unique id ' 
        + searchTerm); 
     return; 
    } 
    return threadIds[0]; 
    } 

我懷疑我們有赴湯蹈火的原因是API的作者不想讓發送電子郵件同步(也許它可以花費太長的時間),因此他們沒有辦法返回一個錯誤或失敗或成功時的消息ID。

如果你想完全瘋狂,你可以用uuid給自己發一條消息,然後在一個while-sleep-search循環中旋轉,直到找到uuid並因此得到一個線程id,然後回覆線程與收件人的完整列表。這可以確保只有您的收件箱在出現問題時纔會受到影響。

相關問題