UNPKG

@cocalc/server

Version:

CoCalc server functionality: functions used by either the hub and the next.js server

59 lines (56 loc) 2.21 kB
"use strict"; /* We use the official V3 Sendgrid API: https://www.npmjs.com/package/@sendgrid/mail The cocalc ASM group numbers are at https://app.sendgrid.com/suppressions/advanced_suppression_manager */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSendgrid = void 0; const pool_1 = __importDefault(require("@cocalc/database/pool")); const mail_1 = __importDefault(require("@sendgrid/mail")); const help_1 = __importDefault(require("./help")); const footer_1 = __importDefault(require("./footer")); const theme_1 = require("@cocalc/util/theme"); // Init throws error if we can't initialize Sendgrid right now. // It also updates the key if it changes in at most one minute (?). let initialized = 0; async function getSendgrid() { const now = new Date().valueOf(); if (now - initialized < 1000 * 30) { // initialized recently return mail_1.default; } const pool = (0, pool_1.default)("long"); const { rows } = await pool.query("SELECT value FROM server_settings WHERE name='sendgrid_key'"); if (rows.length == 0 || !rows[0]?.value) { if (initialized) { // no key now, but there was a key before -- so clear it and error mail_1.default.setApiKey(""); } throw Error("no sendgrid key"); } mail_1.default.setApiKey(rows[0].value); initialized = new Date().valueOf(); return mail_1.default; } exports.getSendgrid = getSendgrid; async function sendEmail(message) { const sg = await getSendgrid(); const msg = await (0, footer_1.default)(message); if (!msg.from) { msg.from = await (0, help_1.default)(); // fallback } if (msg.asm_group) { msg.asm = { group_id: msg.asm_group }; delete msg.asm_group; } // plain template with a header (cocalc logo), a h1 title, and a footer msg.template_id = theme_1.SENDGRID_TEMPLATE_ID; // https://docs.sendgrid.com/api-reference/mail-send/mail-send await sg.send(msg); } exports.default = sendEmail; //# sourceMappingURL=sendgrid.js.map