GAS Import CSV from GMail Attachment

I have a weekly email sent to me with a csv attachment. This needs to be opened and the contents pasted into a google sheet, the data therein is then used for a variety of other applications running on Google sheets. Fortunately there is a way to automate this and to parse the csv to sheets. I have robbed and amended the code provided by Digital Inspiration to do this. The linked page also includes other examples of scraping csv data from an email attachment. The key to getting this to work is a consistent approach by my email sender, who needs to use the same email address and subject in order that the GMail filter I set up can assign a label to the email. The script is run from the receiving google sheet on a timed trigger, once a week.

The sheet needed sorting to meet requirements of others. Above code kept nice and short thanks to the parsing API provided by Google. Of course, this will work for a single user google account, calling on the gmail of that user. Because I have G Suite it is simple to create a separate account to handle this type of thing.


13 thoughts on “GAS Import CSV from GMail Attachment

  1. I’m fairly new to this so I want to clarify a few things. First, this will look at the latest e-mail with a specified label, correct? Where does this code go? On any google sheet? I will need it to pull from my gmail daily.

    • Hi

      Correct, will look at the latest email with the correct label
      The code is run from the google sheet the csv data will be placed in (using script editor)
      You will need to set a trigger to run the script on a daily basis. If the email does not come, the script should run on the latest email with the label regardless. You may need to include some error code and send a an email to inform that the script was successful / unsuccessful.
      Must be same google account for the sheet and the email

  2. Hello,

    I keep getting the error
    TypeError: Cannot call method “getThreads” of null. (line 4, file “Code”)

    Do you know why I might be getting this error?

    • I can only guess that there are no messages in GMail with the correct label applied
      Make sure the messages with attachments you want have the correct label and your script also has that label on that line?

Leave a Reply

Your email address will not be published. Required fields are marked *