diff --git a/firestore-send-email/functions/src/index.ts b/firestore-send-email/functions/src/index.ts index ad88e0a44..33d46d310 100644 --- a/firestore-send-email/functions/src/index.ts +++ b/firestore-send-email/functions/src/index.ts @@ -43,6 +43,15 @@ let transport: nodemailer.Transporter; let templates: Templates; let initialized = false; +/** Unified shape matching Nodemailer’s SendMailInfo */ +interface SendMailInfoLike { + messageId: string | null; + accepted: string[]; + rejected: string[]; + pending: string[]; + response: string | null; +} + /** * Initializes Admin SDK & SMTP connection if not already initialized. */ @@ -183,7 +192,7 @@ async function preparePayload(payload: DocumentData): Promise { uids = uids.concat(payload.bccUids); } - const toFetch = {}; + const toFetch: Record = {}; uids.forEach((uid) => (toFetch[uid] = null)); const documents = await db.getAll( @@ -195,7 +204,7 @@ async function preparePayload(payload: DocumentData): Promise { } ); - const missingUids = []; + const missingUids: string[] = []; documents.forEach((documentSnapshot) => { if (documentSnapshot.exists) { @@ -257,8 +266,9 @@ async function preparePayload(payload: DocumentData): Promise { * * @param payload the payload from Firestore. */ - -async function sendWithSendGrid(payload: DocumentData) { +async function sendWithSendGrid( + payload: DocumentData +): Promise { sgMail.setApiKey(config.smtpPassword); const formatEmails = (emails: string[]) => emails.map((email) => ({ email })); @@ -312,7 +322,21 @@ async function sendWithSendGrid(payload: DocumentData) { logs.info("SendGrid message payload constructed", { msg }); // Send the message using SendGrid's API - return sgMail.send(msg); + const [response /*: ClientResponse*/] = await sgMail.send(msg); + const messageId = + ((response.headers["x-message-id"] || + response.headers["X-Message-Id"]) as string) || null; + const acceptedList = payload.to.map((r) => + typeof r === "string" ? r : (r as any).email + ); + + return { + messageId, + accepted: acceptedList, + rejected: [], + pending: [], + response: `status=${response.statusCode}`, + }; } async function deliver(ref: DocumentReference): Promise { @@ -350,7 +374,7 @@ async function deliver(ref: DocumentReference): Promise { ); } - let result; + let result: SendMailInfoLike; // Automatically detect SendGrid if (isSendGrid(config)) { @@ -363,7 +387,7 @@ async function deliver(ref: DocumentReference): Promise { msg: payload, }); // Use the default transport for other SMTP providers - result = await transport.sendMail({ + result = (await transport.sendMail({ ...Object.assign(payload.message ?? {}, { from: payload.from || config.defaultFrom, replyTo: payload.replyTo || config.defaultReplyTo, @@ -372,7 +396,7 @@ async function deliver(ref: DocumentReference): Promise { bcc: payload.bcc, headers: payload.headers || {}, }), - }); + })) as unknown as SendMailInfoLike; } const info = {