Search code examples
google-apps-scriptgoogle-sheetsgmail

Only XML files to GDrive


I receive emails with attachments in PDF and XML, the code I'm using today records both files in GDrive, I want to send only the XML to GDrive.

var label = GmailApp.getUserLabelByName('NFs'); // <-- RENAME TO YOUR CUSTOM FILTER LABEL
var moveToLabel = GmailApp.getUserLabelByName('NFs Import'); // <-- Uncomment to move to new label after download
var ss = SpreadsheetApp.openById('19vKRsoFwVyXOxvWkE'); //  <-- INSERT GSHEET_ID
var sh = ss.getSheetByName("Email");  //  <-- Enter Sheet-Name where records should be created
var destinationFolderID = '1noxxKIgg4N3G0Ob'; // <-- Enter the ID of the folder to copy files to
var threads = label.getThreads();
threads.forEach(thread => {
  var messages = thread.getMessages();
  messages.forEach(message => {
    var sent = message.getDate();
    var sender = message.getFrom();
    var subject = message.getSubject();
    var attachments = message.getAttachments({
      includeInlineImages: false,
      includeInlineAttachments: false
    });
    var attachmentNames = [];
    attachments.forEach(attachment => {
      Drive.Files.insert({ title: attachment.getName(), mimeType: attachment.getContentType(), parents: [{ id: destinationFolderID }] }, attachment.copyBlob());
      attachmentNames.push([attachment.getName()]);
    });

Solution

  • I believe your goal is as follows.

    • You want to create only XML file from attachments.

    In this case, how about checking the mimeType or the extension of the filename? When this is reflected in your script, please modify as follows.

    From:

    attachments.forEach(attachment => {
    Drive.Files.insert({ title: attachment.getName(), mimeType: attachment.getContentType(), parents: [{ id: destinationFolderID }] }, attachment.copyBlob());
    
        
        attachmentNames.push([attachment.getName()]);
        
    });
    

    To:

    attachments.forEach(attachment => {
      if (attachment.getContentType().toLowerCase().includes("xml") || attachment.getName().toLowerCase().includes(".xml")) {
        Drive.Files.insert({ title: attachment.getName(), mimeType: attachment.getContentType(), parents: [{ id: destinationFolderID }] }, attachment.copyBlob());
        attachmentNames.push([attachment.getName()]);
      }
    });
    

    or

    attachments.forEach(attachment => {
      if (attachment.getContentType() != MimeType.PDF) {
        Drive.Files.insert({ title: attachment.getName(), mimeType: attachment.getContentType(), parents: [{ id: destinationFolderID }] }, attachment.copyBlob());
        attachmentNames.push([attachment.getName()]);
      }
    });
    
    • By this modification, the XML data or the file except for PDF data are created as a file.

    Note:

    • In your showing script, 2 forEach are not enclosed. I'm not sure about your actual script. But, please be careful about this.

    References: