0

Create Draft Email

by
Published today

Create a draft in the Drafts folder, with optional recipients and file attachments from object storage (about 3 MB in total). Returns the draft message; send it with Send Draft. Requires Mail.ReadWrite (a connection default).

Script ms_outlook Verified

The script

Submitted by hugo989 Bun
Verified 1 hour ago
1
import * as wmill from "windmill-client"
2
import { S3Object } from "windmill-client"
3

4
/**
5
 * Create Draft Email
6
 * Create a draft in the Drafts folder, with optional recipients and file attachments from object storage (about 3 MB in total). Returns the draft message; send it with Send Draft. Requires Mail.ReadWrite (a connection default).
7
 */
8
export async function main(
9
  auth: RT.MsOutlook,
10
  subject: string,
11
  body: string,
12
  content_type: "HTML" | "Text" = "HTML",
13
  to: string[] | undefined,
14
  cc: string[] | undefined,
15
  bcc: string[] | undefined,
16
  attachments: S3Object[] | undefined,
17
  mailbox: string | undefined
18
) {
19
  const base = `https://graph.microsoft.com/v1.0/${
20
    mailbox != null && mailbox !== ""
21
      ? `users/${encodeURIComponent(mailbox)}`
22
      : "me"
23
  }`
24
  const recipients = (addresses: string[] | undefined) =>
25
    (addresses ?? [])
26
      .filter((a) => a != null && a.trim() !== "")
27
      .map((address) => ({ emailAddress: { address } }))
28

29
  const files = []
30
  for (const file of attachments ?? []) {
31
    const bytes = await wmill.loadS3File(file)
32
    if (!bytes) throw new Error(`Could not load ${file.s3}`)
33
    files.push({
34
      "@odata.type": "#microsoft.graph.fileAttachment",
35
      name: file.s3.split("/").pop(),
36
      contentBytes: Buffer.from(bytes).toString("base64"),
37
    })
38
  }
39

40
  const response = await fetch(`${base}/messages`, {
41
    method: "POST",
42
    headers: {
43
      Authorization: `Bearer ${auth.token}`,
44
      "Content-Type": "application/json",
45
      Accept: "application/json",
46
    },
47
    body: JSON.stringify({
48
      subject,
49
      body: { contentType: content_type, content: body },
50
      toRecipients: recipients(to),
51
      ccRecipients: recipients(cc),
52
      bccRecipients: recipients(bcc),
53
      attachments: files,
54
    }),
55
  })
56

57
  if (!response.ok) {
58
    throw new Error(`${response.status} ${await response.text()}`)
59
  }
60

61
  return await response.json()
62
}
63