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

Send an email using Gmail without any attachments.

Created by rossmccrann 624 days ago Viewed 9345 times
0
Submitted by adam186 Deno
Verified 513 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
export async function main(
10
  gmail_auth: Gmail,
11
  to_email: string,
12
  subject: string,
13
  message: string,
14
  user_id: string = "me",
15
) {
16
  const token = gmail_auth["token"];
17
  if (!token) {
18
    throw Error(`
19
    No authentication token was found.
20
    Go to "https://app.windmill.dev/resources?connect_app=gmail" to connect Gmail, 
21
    then select your token from the dropdown in the arguments window.
22
    (Click "Refresh" if you don't see your resource in the list.)\n`);
23
  }
24

25
  const text = `From: <${user_id}>\nTo: <${to_email}>\nSubject: ${subject}\n\r ${message}`;
26
  const textEncoder = new TextEncoder();
27
  const email = base64UrlEncode(textEncoder.encode(text));
28
  const body = JSON.stringify({
29
    raw: email,
30
  });
31
  const SEND_URL = `https://gmail.googleapis.com/gmail/v1/users/${user_id}/messages/send`;
32

33
  const response = await fetch(SEND_URL, {
34
    method: "POST",
35
    headers: { Authorization: "Bearer " + token },
36
    body,
37
  });
38

39
  const result = await handleSendEmailResult(await response.json(), to_email);
40
  return result;
41
}
42

43
async function handleSendEmailResult(result: object, to_email: string) {
44
  if (Object.keys(result).includes("error")) {
45
    return Promise.reject({ wm_to_email: to_email, ...result });
46
  }
47

48
  return result;
49
}
50

Other submissions