Search code examples
javascriptgoogle-apps-scriptgmail-api

How to condition the existance of attachments in Google Apps Script (Gmail API)?


in my Apps Script Addon I have this code that send emails and the user can select with a switch button if they want to attach files or not (switch is the emailAttach variable). When the switch is off, file variable is empty and I get console error: "Non valid argument: attachments". I've also tried using [file] || [], or [file] || [''] (like the name parameter, for example), but the error persists.

    let file;
    if (emailAttach) {
      file = DriveApp.getFileById(fileID);
    }

    mailId = GmailApp.createDraft(adress, emailSubject, '', {
      name: emailSender || 'My Company',
      cc: emailSpecific,
      bcc: emailBCC,
      replyTo: emailReplyTo,
      htmlBody: emailBodyMessage,
      attachments: [file],
    }).send().getId();

Right now I have this if/else, useful but ugly and duplicated code, how could I set condition to the attachment in just one "createDraft"?

  let mailId;
  if (emailAttach) {
    
    file = DriveApp.getFileById(fileID);

    mailId = GmailApp.createDraft(adress, emailSubject, '', {
      name: emailSender || 'My Company',
      cc: emailSpecific,
      bcc: emailBCC,
      replyTo: emailReplyTo,
      htmlBody: emailBodyMessage,
      attachments: [file],
    }).send().getId();

  } else {

    mailId = GmailApp.createDraft(adress, emailSubject, '', {
      name: emailSender || 'My Company',
      cc: emailSpecific,
      bcc: emailBCC,
      replyTo: emailReplyTo,
      htmlBody: emailBodyMessage,
    }).send().getId();
  }

Thanks


Solution

  • Declare "options" before the if statement without the attachments property, then add the attachments property when the if condition is true.

    
    let mailId;
    let options =  {
          name: emailSender || 'My Company',
          cc: emailSpecific,
          bcc: emailBCC,
          replyTo: emailReplyTo,
          htmlBody: emailBodyMessage
        };
      if (emailAttach) {
        
        file = DriveApp.getFileById(fileID);
        options.attachments = [file]
        
      } else {
    
        // do nothing
     
      }
    
      mailId = GmailApp.createDraft(adress, emailSubject, '', options).send().getId();