import getPool from "@cocalc/database/pool" ; import sgMail from "@sendgrid/mail" ; import type { Message } from "./message" ; import getHelpEmail from "./help" ; import appendFooter from "./footer" ; import { SENDGRID_TEMPLATE_ID } from "@cocalc/util/theme" ; let initialized = 0 ; export async function getSendgrid ( ) { const now = new Date ( ) . valueOf ( ) ; if ( now - initialized < 1000 * 30 ) { return sgMail ; } const pool = getPool ( "long" ) ; const { rows } = await pool . query ( "SELECT value FROM server_settings WHERE name='sendgrid_key'" ) ; if ( rows . length == 0 || ! rows [ 0 ] . value ) { if ( initialized ) { sgMail . setApiKey ( "" ) ; throw Error ( "no sendgrid key" ) ; } } sgMail . setApiKey ( rows [ 0 ] . value ) ; initialized = new Date ( ) . valueOf ( ) ; return sgMail ; } export default async function sendEmail ( message ) { const sg = await getSendgrid ( ) ; const msg = await appendFooter ( message ) ; if ( ! msg . from ) { msg . from = await getHelpEmail ( ) ; } if ( msg . asm_group ) { msg . asm = { group_id : msg . asm_group } ; delete msg . asm_group ; } msg . template_id = SENDGRID_TEMPLATE_ID ; await sg . send ( msg ) ; }