import { encode as base64UrlEncode } from "https://deno.land/std@0.82.0/encoding/base64url.ts";
/**
* @param user_id User's email address. The special value `me` can be used to indicate the authenticated user.
*/
type Gmail = {
token: string;
};
export async function main(
gmail_auth: Gmail,
to_email: string,
subject: string,
message: string,
file_name: string,
file_content: string,
user_id: string = "me",
) {
const token = gmail_auth["token"];
if (!token) {
throw Error(`
No authentication token was found.
Go to "https://app.windmill.dev/resources?connect_app=gmail" to connect Gmail,
then select your token from the dropdown in the arguments window.
(Click "Refresh" if you don't see your resource in the list.)\n`);
}
const boundary = "boundary_string";
const text = [
`Content-Type: multipart/mixed; boundary="${boundary}"\r\n`,
'MIME-Version: 1.0\r\n',
`From: ${user_id}\r\n`,
`To: ${to_email}\r\n`,
`Subject: ${subject}\r\n\r\n`,
`--${boundary}\r\n`,
'Content-Type: text/plain; charset="UTF-8"\r\n',
'MIME-Version: 1.0\r\n',
'Content-Transfer-Encoding: 7bit\r\n\r\n',
`${message}\r\n\r\n`,
`--${boundary}\r\n`,
'Content-Type: application/octet-stream\r\n',
'MIME-Version: 1.0\r\n',
'Content-Transfer-Encoding: base64\r\n',
`Content-Disposition: attachment; filename="${file_name}"\r\n\r\n`,
`${file_content}\r\n\r\n`,
`--${boundary}--`
].join('');
const textEncoder = new TextEncoder();
const email = base64UrlEncode(textEncoder.encode(text));
const body = JSON.stringify({
raw: email,
});
const SEND_URL =
`https://gmail.googleapis.com/gmail/v1/users/${user_id}/messages/send?uploadType=multipart`;
const response = await fetch(SEND_URL, {
method: "POST",
headers: { Authorization: "Bearer " + token },
body,
});
const result = await handleSendEmailResult(await response.json(), to_email);
return result;
}
async function handleSendEmailResult(result: object, to_email: string) {
if (Object.keys(result).includes("error")) {
return Promise.reject({ wm_to_email: to_email, ...result });
}
return result;
}
Submitted by nicolas.michel228 122 days ago