//native
/**
* Create Draft
* Save an unsent draft in the connected Gmail account. Set `is_html` to send `body` as HTML. To draft a reply, pass the original's `thread_id` and its `Message-ID` header as `in_reply_to` and keep the same subject.
*/
export async function main(
auth: RT.Gmail,
to: string,
subject: string,
body: string,
cc: string | undefined,
bcc: string | undefined,
is_html: boolean = false,
thread_id: string | undefined,
in_reply_to: string | undefined
) {
const headers = [
`To: ${to}`,
cc ? `Cc: ${cc}` : undefined,
bcc ? `Bcc: ${bcc}` : undefined,
`Subject: =?UTF-8?B?${base64(subject)}?=`,
in_reply_to ? `In-Reply-To: ${in_reply_to}` : undefined,
in_reply_to ? `References: ${in_reply_to}` : undefined,
"MIME-Version: 1.0",
`Content-Type: text/${is_html ? "html" : "plain"}; charset="UTF-8"`,
"Content-Transfer-Encoding: base64",
].filter((h) => h !== undefined)
const mime = `${headers.join("\r\n")}\r\n\r\n${base64(body)}`
const raw = base64(mime).replace(/\+/g, "-").replace(/\//g, "_")
const response = await fetch(
"https://gmail.googleapis.com/gmail/v1/users/me/drafts",
{
method: "POST",
headers: {
Authorization: `Bearer ${auth.token}`,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
message: { raw, threadId: thread_id || undefined },
}),
}
)
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
return await response.json()
}
function base64(s: string) {
const bytes = new TextEncoder().encode(s)
let binary = ""
for (const b of bytes) binary += String.fromCharCode(b)
return btoa(binary)
}
Submitted by hugo989 4 hours ago