Edits history of script submission #23025 for ' Get Message (gmail)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Get Message
     * Get a Gmail message by ID. With the default `full` format the decoded plain-text body is added as `body_text` (falling back to the HTML body when there is no plain-text part).
     */
    export async function main(
      auth: RT.Gmail,
      message_id: string,
      format: "full" | "metadata" | "minimal" | "raw" = "full"
    ) {
      const url = new URL(
        `https://gmail.googleapis.com/gmail/v1/users/me/messages/${message_id}`
      )
      url.searchParams.append("format", format)
    
      const response = await fetch(url, {
        headers: {
          Authorization: `Bearer ${auth.token}`,
          Accept: "application/json",
        },
      })
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const message = await response.json()
      if (message.payload) {
        message.body_text =
          findBody(message.payload, "text/plain") ??
          findBody(message.payload, "text/html")
      }
      return message
    }
    
    type Part = { mimeType: string; body?: { data?: string }; parts?: Part[] }
    
    function findBody(part: Part, mimeType: string): string | undefined {
      if (part.mimeType === mimeType && part.body?.data) {
        const b64 = part.body.data.replace(/-/g, "+").replace(/_/g, "/")
        return new TextDecoder().decode(
          Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))
        )
      }
      for (const p of part.parts ?? []) {
        const found = findBody(p, mimeType)
        if (found !== undefined) return found
      }
    }
    

    Submitted by hugo989 4 hours ago