Openpieces logoopenpieces
All contributors
SW

Sam Wilson

@swilson

Full-Stack Engineer

Email and communication APIs. Building the Gmail and Outlook pieces. Previously at Superhuman.

London, UKJoined October 5, 2024github/swilson

1

Piece published

1,532

Total installs

87

Avg AI Score

Pieces by Sam Wilson

gmail-parse

Communication

Fetch and parse Gmail messages via the Gmail API. Extracts body, attachments, and headers with OAuth2 token refresh built in.

GmailGoogle
87891swilson14mo ago
1import{serve}from"https://deno.land/std@0.224.0/http/server.ts";
2 
3interfaceGmailQuery{
4query:string;
5maxResults?:number;
6}
7 
8constACCESS_TOKEN=Deno.env.get("GMAIL_ACCESS_TOKEN")!;
9 
10asyncfunctionfetchMessages(req:Request):Promise<Response>{
11const{query,maxResults=10}:GmailQuery=awaitreq.json();
12 
13constlistUrl=newURL("https://gmail.googleapis.com/gmail/v1/users/me/messages");
14listUrl.searchParams.set("q",query);
15listUrl.searchParams.set("maxResults",String(maxResults));
16 
17constlistRes=awaitfetch(listUrl.toString(),{
18headers:{Authorization:`Bearer ${ACCESS_TOKEN}`},
19});
20 
21if(!listRes.ok){
22returnnewResponse(
23JSON.stringify({error:"Failed to list messages"}),
24{status:listRes.status}
25);
26}
27 
28const{messages=[]}=awaitlistRes.json();
29constdetailed=awaitPromise.all(
30messages.map(async(m:{id:string})=>{
31constmsgRes=awaitfetch(
32`https://gmail.googleapis.com/gmail/v1/users/me/messages/${m.id}`,
33{headers:{Authorization:`Bearer ${ACCESS_TOKEN}`}}
34);
35constmsg=awaitmsgRes.json();
36constheaders=msg.payload.headers.reduce(
37(acc:Record<string,string>,h:{name:string;value:string})=>{
38acc[h.name]=h.value;
39returnacc;
40},
41{}
42);
43constbody=
44msg.payload.parts?.[0]?.body?.data
45?atob(msg.payload.parts[0].body.data.replace(/-/g,"+").replace(/_/g,"/"))
46:"";
47return{id:m.id,headers,snippet:msg.snippet,body};
48})
49);
50 
51returnnewResponse(JSON.stringify(detailed),{
52headers:{"content-type":"application/json"},
53});
54}
55 
56serve(fetchMessages,{port:8080});