Tomer
Tomer

Reputation: 1568

Automated XML fetch into specific Google spreadsheet

I'm working on a piece of code that can contribute a lot to my process at work. I receive a single mail to some label in my Gmail on daily basis with a single xml attachment which I want to fetch it into specific spreadsheet. What I'm trying to build is a script with google app script which will be able to:

  1. locate a specific label in my Gmail (Label_Name)
  2. Find the attachment from the unread mail within that label (XML File)
  3. Fetch the attachment data (XML) into a specific google spreadsheet in my google drive.

My code looks like this:

function RetrieveFeedAttachment() {
  var label = GmailApp.getUserLabelByName("Label_Name");
  var threads = label.getThreads();
  var feed = SpreadsheetApp.openById("The_Specific_Spreadsheet_ID").getSheetByName("Spreadsheet_Name");
  feed.clearContents();

  for (var i = 0; i < threads.length; i++) {
    if (threads[i].isUnread()) {
      var msg = GmailApp.getMessagesForThread(threads[i]);
      var xmlDoc = XmlService.parse(msg[0].getAttachments());
      for(var j = 0; j < msg.length; j++) {
        feed.appendRow(xmlDoc.getContent(j));
      }
     threads[i].markRead();
    }
  }
}

When I ran the script debugger it showed me the following notification "Error on line 1: Content is not allowed in prolog. (line 10, file "Code")"

Thank you for advising\helping!

Upvotes: 1

Views: 325

Answers (1)

user6655984
user6655984

Reputation:

The method getAttachments() returns an array of attachments. That's not an XML file that XmlService can parse. The method XmlService.parse() accepts a string.

If you can assume there is exactly one attachment, then

msg[0].getAttachments()[0].getDataAsString()

should get you a string that you can parse with XmlService.parse(). Otherwise, loop over the array of attachments.

You may also want to put XmlService.parse() into a try-catch block in case a message with a non-XML attachment comes along.

Upvotes: 1

Related Questions