4
Send Email
One script reply has been approved by the moderators Verified

Send an email using Gmail without any attachments.

Created by rossmccrann 834 days ago Viewed 18117 times
0
Submitted by henri186 Deno
Verified 154 days ago
1
import { encode as base64UrlEncode } from "https://deno.land/std@0.82.0/encoding/base64url.ts";
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.windmill.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

Other submissions