-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgmail_service.ts
80 lines (70 loc) · 2.09 KB
/
gmail_service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { OAuth2Client } from "https://deno.land/x/oauth2_client/mod.ts";
interface GmailMessage {
payload: {
headers: Array<{
name: string;
value: string;
}>;
};
}
export class GmailService {
private oauth2Client: OAuth2Client;
constructor() {
this.oauth2Client = new OAuth2Client({
clientId: Deno.env.get("GOOGLE_CLIENT_ID")!,
clientSecret: Deno.env.get("GOOGLE_CLIENT_SECRET")!,
redirectUri: "http://localhost:8080/callback",
authorizationEndpointUri: "https://accounts.google.com/o/oauth2/v2/auth",
tokenUri: "https://oauth2.googleapis.com/token",
defaults: {
scope: ["https://www.googleapis.com/auth/gmail.readonly"],
},
});
}
async getRecentEmails(maxResults = 10) {
const accessToken = await this.getAccessToken();
const response = await fetch(
`https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=${maxResults}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const data = await response.json();
const emails = await Promise.all(
(data.messages ?? []).map((message: { id: string }) =>
this.getEmailDetails(message.id, accessToken)
)
);
return emails;
}
private async getEmailDetails(messageId: string, accessToken: string) {
const response = await fetch(
`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const data = await response.json();
return {
id: data.id,
subject: this.getHeader(data, "Subject"),
from: this.getHeader(data, "From"),
date: this.getHeader(data, "Date"),
snippet: data.snippet,
};
}
private getHeader(message: GmailMessage, name: string) {
return message.payload.headers.find(
(header) => header.name === name
)?.value;
}
private getAccessToken() {
// You'll need to implement token management
// This is a simplified version
return Deno.env.get("GMAIL_ACCESS_TOKEN")!;
}
}