简体   繁体   中英

Creating multiple gmail drafts from a google sheet (I can only create one at a time from the most recent entry to the sheet)

I tried to have the createDraft method pull from variable that are able to return all of the column values but was unable to have it create multiple drafts at once. I am using a tracking pixel that attaches to draft emails before being sent to track when the user on the receiving end opens the email.

function onOpen() {
    let menu = SpreadsheetApp.getUi().createMenu("Sheet Functions");
    menu.addItem("Create draft (From Responses tab)" , "getDrafts");
    menu.addItem("Refresh Draft List (Check the box for desired email on drafts page)", "createDraftTemplate")
    menu.addItem("Send Draft List (Only selected drafts will be sent)", "sendButton")
    menu.addToUi();
}`your text`

function createDraftTemplate () {
    var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var sheetValues = ss.getDataRange().getValues();

    for (let i = 1; i < sheetValues.length; i++) {
        var row = sheetValues[i];
        var timeStamp = row[0];
        var fuName = row[1];
        var currentEmail = row[2];
        var dscrptn = row[3];
        var crctn = row[4];
    }

    // create draft
    var now = new Date();
    GmailApp.createDraft( currentEmail , "Test", "Employee:  " + fuName.toString() + "\n\nWas described performing actions which require corrective action: " + dscrptn.toString() + "\n\nManagement requirements for correction: " + crctn.toString());
}

function getDrafts() {
    // Store a reference to the current spreadsheet that the script is tied to
    var spreadSheet = SpreadsheetApp.getActive()

    // Store a reference to the Drafts tab 
    var draftSheet = spreadSheet.getSheetByName("Drafts")

    // Reset the Send? column by clearing it all, including the data validation (checkbox)
    draftSheet.getDataRange().clear().clearDataValidations()

    // Retrieve from Gmail the full list of drafts in the Drafts folder
    var drafts = GmailApp.getDrafts()

    // Set up the array that will output the information back to the sheet and include the headers as the first row
    var draftsOutput = [["Subject","To","ID","Send ?"]]

    // Loop throuhg all the drafts return from Gmail
    for (var i = 0; i<drafts.length; i++) {
        //Store the current draft for ease and clarity
        var draft = drafts[i]

        // Add the Subject, To line, unique ID, and a false value to uncheck the checkbox to the output array
        draftsOutput.push([draft.getMessage().getSubject(),draft.getMessage().getTo(), draft.getId(),false])
    }

    // Using the array’s length and breadth, pass the array of drafts to the Drafts sheet
    draftSheet.getRange(1, 1, draftsOutput.length, draftsOutput[0].length).setValues(draftsOutput)

    // Create a new data validation in the form of checkboxes in the  last column of the sheet (the "Send ?" column)
    draftSheet.getRange(2,draftsOutput[0].length,draftsOutput.length).setDataValidation(SpreadsheetApp.newDataValidation()
        .setAllowInvalid(true)
        .requireCheckbox()
        .build());
}

function getTrackingGIF(email, subject) {
    // Create a url based on the Email Tracker Webhook web app's URL and attaching two URL paramaters 
    // that will pass the Subject and the To line of the email to the web app. Replace [WEBAPP URL] below with the URL of your web app
    var imgURL = "https://script.google.com/macros/s/AKfycbzTqs-Fn444uqxvSRT1DWd7mMbJzStNzmTmkuyl105d95s1S4-qkR1_VxlBLWI0fjjO/exec"

    // encode the Subject to assure that it will be passed properly as a part of a URL 
    + "?esubject=" + encodeURIComponent(subject.replace(/'/g, ""))
    // encode the To line to assure that it will be passed properly as a part of a URL
    + "&eto=" + encodeURIComponent(email);
  //Return an HTML tag for a 1x1 pixel image with the image source as the web app's URL 
  return "<img src='" + imgURL + "' width='1' height='1'/>";
}
function sendMail(draftId) { 
  // Retrieve a reference to the specific draft by the unique ID, draftId
  var draft = GmailApp.getDraft(draftId)
  // Store the Message object of the draft 
  var message = draft.getMessage()
  // Store the actual contents of the drafts, or the body of the message
  var body = message.getBody();
  // Add the HTML code ofr the tracking image by calling the getTrackingGIF function
  // and passing the draft's To line and Subject line
  body += getTrackingGIF(message.getTo(), message.getSubject());
  // Update the draft with the new body while making sure that all other info remains the same
  draft.update(message.getTo(), message.getSubject(), body, {
    htmlBody: body, 
    cc: message.getCc(), 
    bcc: message.getBcc(), 
    attachments: message.getAttachments()})
  // Send the draft
  draft.send()
  // Refresh the updated Drafts folder to show the draft was sent
  getDrafts()
}
function sendButton() {
  // Store a reference to the current spreadsheet that the script is tied to
  var spreadSheet = SpreadsheetApp.getActive()
  // Store a reference to the Drafts tab 
  var draftSheet = spreadSheet.getSheetByName("Drafts")
  // Store all the information in the Range of cells that has data within the Drafts tab
  var draftRange = draftSheet.getDataRange().getValues()
  // Loop through all the rows in the Drafts tab
  for (var i=0; i<draftRange.length; i++) {
    // check if any row has a check mark (is true) in the Send? column, 
    // and pass the unique id of the draft to the sendMail function to send it if true  
    if (draftRange[i][3]==true) sendMail(draftRange[i][2])
  }
  //Reset the Send? column by clearing its content
  draftSheet.getRange(2,4,draftRange.length-1).clearContent()  
}
function doGet(e) {
 // Store a reference for the tracking spreadsheet
 var trackingSpSheet = SpreadsheetApp.openById("1wKetTiUYphmegm7S0YTEU61TohukEbweY1F6iV7M3Sw")
 // Store a reference for the Logs sheet
 var outputSheet = trackingSpSheet.getSheetByName("Logs")
// Get the number of the last row in the Logs sheet with no content
 var lastRow = outputSheet.getLastRow()+1
// Set the value of the last row to the current date and the email info
 outputSheet.getRange(lastRow, 1,1,3).setValues([[new Date(),e.parameters.esubject,e.parameters.eto]])
// Return a string version of e to comply with the web app requirement
return ContentService.createTextOutput(JSON.stringify(e)) 
}

The problem is that

//create draft
var now = new Date();
GmailApp.createDraft( currentEmail , "Test", "Employee:  " + fuName.toString() + "\n\nWas described performing actions which require corrective action: " + dscrptn.toString() + "\n\nManagement requirements for correction: " + crctn.toString());

is not included inside the code block of the for loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM