0
votes

Trying to alter the following script to prompt for an email address. I was able to load this as an add-on in Google sheets and it works fine but I want to be able to change the "To" address each time I run it. Is there any way to force some sort of prompt so that I can input the email address on each run?

    function onOpen() { 
  // Try New Google Sheets method
  try{
    var ui = SpreadsheetApp.getUi();
    ui.createMenu('SendMail')
    .addItem('Send Report', 'getGoogleSpreadsheetAsExcel')
    .addToUi(); 
  }

  // Log the error
  catch (e){Logger.log(e)}

}

function getGoogleSpreadsheetAsExcel(){

  try {

    var ss = SpreadsheetApp.getActive();

    var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=csv";

    var params = {
      method      : "get",
      headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions: true
    };

    var blob = UrlFetchApp.fetch(url, params).getBlob();

    blob.setName(ss.getName() + ".csv");

    MailApp.sendEmail("[email protected]", "Stock report of today", "The XLSX file is attached", {attachments: [blob]});

  } catch (f) {
    Logger.log(f.toString());
  }
}
1

1 Answers

1
votes

All you need to do is get the UI of the spreadsheet and send a prompt then run it through an if statement to make sure the correct button is pressed, try the below:

function getGoogleSpreadsheetAsExcel(){

  try {

    var ss = SpreadsheetApp.getActive();

    var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=csv";

    var params = {
      method      : "get",
      headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions: true
    };

    var blob = UrlFetchApp.fetch(url, params).getBlob();

    blob.setName(ss.getName() + ".csv");

    var ui = SpreadsheetApp.getUi();
    var prompt = ui.prompt('Enter email address:', '',ui.ButtonSet.OK_CANCEL);

    if (prompt.getSelectedButton() == 'OK') {

      var mail = prompt.getResponseText();
      MailApp.sendEmail(mail, "Stock report of today", "The XLSX file is attached", {attachments: [blob]});
    }

  } catch (f) {
    Logger.log(f.toString());
  }
}

The code prompts for an email address:

var prompt = ui.prompt('Enter email address:', '',ui.ButtonSet.OK_CANCEL);

Then runs through a quick if statement to make sure the button pressed is 'OK', if it's cancelled it'll do nothing.

if (prompt.getSelectedButton() == 'OK') {

  var mail = prompt.getResponseText();
  MailApp.sendEmail(mail, "Stock report of today", "The XLSX file is attached", {attachments: [blob]});
}

As you can see, var mail is used in the sendEmail(), meaning it'll use whatever you entered as your email address as the recipient of your email.