google-apps-scriptgmailgoogle-workspace-add-ons

How to get current message Id in Gmail using AppScript?


So, I was looking around the internet for a code to get the current message Id or just current message but I cannot seem to find it. What I actually want is, when I click on a mail and open it, the add-on I am working on should be able to get the message or the message id so that I can get hold of some information from that mail. How do I do it? I tried few things but cannot seem to get it working. Any idea? any suggestion is greatly appreciated, Thanks.


Solution

  • So, I did solve it and all thanks to @TheMaster for his help. So, What I did was I edited the manifest file and then added the code in my code.gs file. This is what I added in my Manifest file,

    "addOns": {
        "common": {
          "name": "Attatchment Downloader",
          "logoUrl": "URL FOR LOGO"
        },
        "gmail": {
          "contextualTriggers": [
            {
              "unconditional": {},
              "onTriggerFunction": "onGmailMessageOpen"
            }
          ]
        }
      }
    

    You can enable the manifest file to be displayed along with other files by going to project settings and enabling it there.

    and then the onGMailMessageOpen function inside the code.gs file. So when the user opens any message, this function is automatically called and an eventobject is passed to it. So using this event object we can access the EMail/Message that is currently open, but first you will need to get the access token like the code below and get hold of the current message and its Id.

    function onGmailMessageOpen(eventObject){
      // Activate temporary Gmail scopes, in this case to allow
      // message metadata to be read.
      var accessToken = eventObject.gmail.accessToken;
      GmailApp.setCurrentMessageAccessToken(accessToken);
    
      var messageId = eventObject.gmail.messageId;
    }
    

    you can also get all of these from the official documentation, through this link,

    https://developers.google.com/apps-script/reference/gmail ,

    you might have to find what your looking for as there is lot to take in.