title: How to extract an attachment from an email to a shared drive that is in a google sheets?
body: <p>currently I have a google script that runs every x times on my Gmail which retrieves all attachments according to of the label.
  I enter the email addresses and the path of the folder via a <code>getFolderByName</code> in a google sheets but the problem is that this does not work if the folder is on a shared drive.</p>
  <p>I saw different topic on the forum so I know I need to use <a href="https://developers.google.com/drive/api/v3/reference/drives/get" rel="nofollow noreferrer">Drive API</a></p>
  <p>So I would like to retrieve the id of my folder which is in my google sheet instead of my <code>getFolderByName</code>.</p>
  <p>Here are the 3 functions:</p>
  <ul>
  <li><code>getLibelleConfigs</code> : Retrieves LibelleConfig objects from the configuration sheet</li>
  <li><code>getFolderFromPath</code> : Get or create a folder from its path</li>
  <li><code>getOrCreateFolder</code> : Recover or create a folder</li>
  </ul>
  <pre class="lang-js prettyprint-override"><code>function getLibelleConfigs() {
      let spreadSheet = getOrCreateSpreadSheet(config.configSheetPath, config.configSheetHeader);
  
      let sheet = spreadSheet.getSheets()[0];
  
      let values = sheet.getDataRange().getValues();
  
      if (values.length == 0 || values.length == 1 &amp;&amp; values[0].length == 1 &amp;&amp; values[0][0] == &quot;&quot;) sheet.appendRow(config.configSheetHeader);
  
      return values
          .filter((row, i) =&gt; {
              return i &gt; 0 &amp;&amp; row.length &gt; 0 &amp;&amp; row[0] != &quot;&quot;;
          })
          .map(row =&gt; {
              let libelle = row[0].trim();
              let folderPath = (row.length&gt;1 &amp;&amp; row[1] != &quot;&quot; ? row[1] : `/${row[0]}`);
              if (!folderPath.startsWith('/')) folderPath = '/' + folderPath;
              folderPath = folderPath.trim();
              return {
                  libelle: libelle,
                  folderPath: folderPath
              }
          });
  }
  </code></pre>
  <pre class="lang-js prettyprint-override"><code>function getFolderFromPath(path)
  {
      let strings = path.split(&quot;/&quot;);
  
      let currentFolder = DriveApp.getRootFolder();
  
      strings.forEach((string, index) =&gt; {
          if (string == &quot;&quot;) return;
          currentFolder = getOrCreateFolder(string, currentFolder);
      });
  
      return currentFolder;
  }
  </code></pre>
  <pre class="lang-js prettyprint-override"><code>function getOrCreateFolder(folderName, parentFolder) {
      
      let folders = parentFolder.getFoldersByName(folderName);
      //Logger.log(&quot;folder : &quot; + folders + &quot;, folderName : &quot; + folderName);
      if (folders.hasNext()) {
          return folders.next();
      }
      else {
          return parentFolder.createFolder(folderName);
      
    }
  }
  </code></pre>
  <p>google sheets :</p>
  <pre><code>+----------------+-----------+
  |     LABEL      | ID FOLDER |
  +----------------+-----------+
  | aaaa@gmail.com | xxxxx_1   |
  | aaaa@gmail.com | xxxxx_3   |
  | bbbb@gmail.com | xxxxx_1   |
  | bbbb@gmail.com | xxxxx_2   |
  +----------------+-----------+
  </code></pre>
  <hr />
  <p>Edit</p>
  <pre class="lang-js prettyprint-override"><code>function saveAttachmentsFromLibelleConfig(libelleConfig, messageIdHistory)
  {
      let threads = GmailApp.search(`in:inbox has:attachment label:${libelleConfig.libelle}`);
      console.info(`${threads.length} ${threads.length &gt; 1 ? 'threads trouvés' : 'thread trouvé'} pour le libellé '${libelleConfig.libelle}'`);
      
      if (threads.length == 0) return;
  
      let parentFolder = getFolderFromPath(libelleConfig.folderPath);
  
      threads.forEach(thread =&gt; {
          try
          {
              thread.getMessages().forEach(message =&gt; {
                  if (messageIdHistory.includes(message.getId())) return;
                  message.getAttachments().forEach(attachment =&gt; {
                      console.info(`Enregistrement de la pièces jointe '${attachment.getName()}' du mail '${message.getSubject()}' - '${message.getId()}' envoyé par '${message.getFrom()}' ayant le libellé '${libelleConfig.libelle}'`);
                      parentFolder.createFile(attachment.copyBlob());
                      appendHistory(message.getId(), libelleConfig.libelle, message.getFrom(), attachment.getName(), libelleConfig.folderPath);
                  });
                  message.markRead();
              });
              thread.moveToArchive();
          }
          catch (e)
          {
              console.warn(`Erreur lors du traitement du thread '${thread.getFirstMessageSubject()}' : ${e}`);
          }
      });
  }
  </code></pre>
  <hr />
  <p>My Solution :</p>
  <pre><code> function movefileToSharedDrive() {
    makeCopy(&quot;My Drive ID&quot;, &quot;To Shared Drive ID&quot;);
    deleteFiles(&quot;My Drive ID&quot;);
  }
  
  function makeCopy(srcFolderId, dstFolderId) {
    var srcFolder = DriveApp.getFolderById(srcFolderId);
    var dstFolder = DriveApp.getFolderById(dstFolderId);
    var files = srcFolder.getFiles();
    while (files.hasNext()) {
      var file = files.next();
      var f = file.makeCopy(dstFolder);
      if (file.getMimeType() == MimeType.GOOGLE_APPS_SCRIPT) {
        Drive.Files.update({&quot;parents&quot;: [{&quot;id&quot;: dstFolderId}]}, f.getId());
      }
    }
  }
  
  function deleteFiles(folderId){
    var folder = DriveApp.getFolderById(folderId);
    var files = folder.getFiles()
    while(files.hasNext()){
      files.next().setTrashed(true)
    }
  }
  </code></pre>
  <p>There are three steps:</p>
  <ol>
  <li>trigger that extracts attachments to my drive</li>
  <li>then function makeCopy to drive shared</li>
  <li>and finally one that deletes files from my drive(to avoid duplicates)</li>
  </ol>