Home > OS >  Concatenate two variables for email subject
Concatenate two variables for email subject

Time:05-14

I am trying to fetch the attachment data from gmail to google sheets with identifier as subject. The subject format is such as "Disbursement File 2022-05-14" where the date is dynamic(i.e current date). I am unable to do so, Please help me with this.

function importReport() {
  var v = "Disbursement File "
  var n = Utilities.formatDate(new Date(), "GMT 5:30", "yyyy-MM-dd");
  var threads = GmailApp.search('in:inbox subject: v n');
  var message = threads[0].getMessages();
  var attachment = message[message.length - 1].getAttachments()[0];
  attachment.setContentType('text/csv');
  if (attachment.getContentType() === "text/csv") {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mail");
    var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
    var header = csvData.splice(0, 1);
    sheet.getRange(sheet.getLastRow()   1, 1, csvData.length, csvData[0].length).setValues(csvData);
  }
}

CodePudding user response:

You can concatenate text strings with the operator like this:

  const threads = GmailApp.search('in:inbox subject: '   v   n);

...or with a template literal, like this:

  const threads = GmailApp.search(`in:inbox subject: ${v}${n}`;

CodePudding user response:

You do not need to setContentType here attachment.setContentType('text/csv'); you can remove that line oF code

Be aware that you can have different ContentType for csv file, check in console the getContentType if applicable

May be add () around the subject according to https://support.google.com/mail/answer/7190 when subject contains many terms

Try

function importReport() {
  // 'Disbursement File 2022-05-14'
  var v = "Disbursement File "
  var n = Utilities.formatDate(new Date(), "GMT 5:30", "yyyy-MM-dd");
  var threads = GmailApp.search(`'in:inbox subject: (${v} ${n})'`);
  var message = threads[0].getMessages();
  var attachment = message[message.length - 1].getAttachments()[0]
  console.log(attachment.getContentType())
  if (attachment.getContentType() === "text/csv") {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mail");
    var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
    var header = csvData.splice(0, 1);
    sheet.getRange(sheet.getLastRow()   1, 1, csvData.length, csvData[0].length).setValues(csvData);
  }
}
  • Related