简体   繁体   中英

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

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();

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