| 1 | //native |
| 2 | |
| 3 | /** |
| 4 | * @param user_id User's email address. The special value `me` can be used to indicate the authenticated user. |
| 5 | */ |
| 6 | type Gmail = { |
| 7 | token: string; |
| 8 | }; |
| 9 | |
| 10 | export async function main( |
| 11 | gmail_auth: Gmail, |
| 12 | to_email: string, |
| 13 | subject: string, |
| 14 | message: string, |
| 15 | user_id: string = "me", |
| 16 | ) { |
| 17 | const token = gmail_auth["token"]; |
| 18 | if (!token) { |
| 19 | throw Error(` |
| 20 | No authentication token was found. |
| 21 | Go to "https://app.orvanta.dev/resources?connect_app=gmail" to connect Gmail, |
| 22 | then select your token from the dropdown in the arguments window. |
| 23 | (Click "Refresh" if you don't see your resource in the list.)\n`); |
| 24 | } |
| 25 | |
| 26 | const text = |
| 27 | `From: <${user_id}>\nTo: <${to_email}>\nSubject: ${subject}\nContent-Type: text/html; charset="UTF-8"\n\r <p>${message}</p>`; |
| 28 | const textEncoder = new TextEncoder(); |
| 29 | const email = base64UrlEncode(textEncoder.encode(text)); |
| 30 | const body = JSON.stringify({ |
| 31 | raw: email, |
| 32 | }); |
| 33 | const SEND_URL = |
| 34 | `https://gmail.googleapis.com/gmail/v1/users/${user_id}/messages/send`; |
| 35 | |
| 36 | const response = await fetch(SEND_URL, { |
| 37 | method: "POST", |
| 38 | headers: { Authorization: "Bearer " + token }, |
| 39 | body, |
| 40 | }); |
| 41 | |
| 42 | const result = await handleSendEmailResult(await response.json(), to_email); |
| 43 | return result; |
| 44 | } |
| 45 | |
| 46 | async function handleSendEmailResult(result: object, to_email: string) { |
| 47 | if (Object.keys(result).includes("error")) { |
| 48 | return Promise.reject({ wm_to_email: to_email, ...result }); |
| 49 | } |
| 50 | |
| 51 | return result; |
| 52 | } |
| 53 | |
| 54 | function base64UrlEncode(data: string | Uint8Array) { |
| 55 | const bytes = |
| 56 | typeof data === "string" ? new TextEncoder().encode(data) : data; |
| 57 | let binary = ""; |
| 58 | for (let i = 0; i < bytes.length; i++) { |
| 59 | binary += String.fromCharCode(bytes[i]); |
| 60 | } |
| 61 | return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); |
| 62 | } |
| 63 | |