"Downloading" in Gmail - returning a .eml file

As part of my workflow I need to download an email stored in Gmail as a .eml file (the equivalent of selecting “download” in the Gmail UI itself). Looking at the gmail node I can’t see an obvious way to do that.

I don’t actually need to “download” it as such, simply get hold of the .eml binary in the workflow so that I can then attach it to another email (for bureaucracy reasons…).

I’ve got as far as getting the correct email returned as JSON data. How can I turn that into a valid .eml file so I can work with it further?

It seems like the raw field contains the base64 encoded email, and it can be saved as a .eml file.

With that in mind, it seems like we need to map the base64 data to binary data in n8n so that you can use it in other nodes. Do the following:

  1. Use the operation message:getAll or get and set the parameter format to raw (it’s under additional fields)

2 - Use a function node to map the raw email to n8n binary data. The function node looks like this:

items[0].binary = { data: {
  fileName: 'file.eml',
  mimeType: 'application/octet-stream',
  data: items[0].json.raw,
} }
return items;

After that, you should be able to use the binary data in other nodes.

Check the example workflow below:

{
  "nodes": [
    {
      "parameters": {},
      "name": "Start",
      "type": "n8n-nodes-base.start",
      "typeVersion": 1,
      "position": [
        250,
        300
      ]
    },
    {
      "parameters": {
        "resource": "message",
        "operation": "get",
        "messageId": "179005639daeae8e",
        "additionalFields": {
          "format": "raw"
        }
      },
      "name": "Gmail",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 1,
      "position": [
        570,
        300
      ],
      "credentials": {
        "gmailOAuth2": "sasasasasas"
      }
    },
    {
      "parameters": {
        "functionCode": "items[0].binary = { data: {\n  fileName: 'file.eml',\n  mimeType: 'application/octet-stream',\n  data: items[0].json.raw,\n} }\nreturn items;"
      },
      "name": "Function",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        850,
        300
      ]
    }
  ],
  "connections": {
    "Start": {
      "main": [
        [
          {
            "node": "Gmail",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail": {
      "main": [
        [
          {
            "node": "Function",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
2 Likes

Thank you, that works perfectly!

Glad that it worked. Have fun.