UNPKG

react-email-sender-adapters

Version:

A unified interface for sending react-email emails across multiple email services.

48 lines (47 loc) 2.93 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { encodeAttachmentToBase64, parseMail } from './tools.js'; export function sendEmail(email, options) { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c; const mail = yield parseMail(email, options); if (!mail) return; const { from, to, cc, bcc, reply_to, text, html } = mail; const url = (_a = options.url) !== null && _a !== void 0 ? _a : process.env.ZEPTOMAIL_URL; const token = (_b = options.token) !== null && _b !== void 0 ? _b : process.env.ZEPTOMAIL_TOKEN; if (!url) throw new Error('No url provided for Zeptomail. You can also set the environment variable `ZEPTOMAIL_URL`.'); if (!token) throw new Error('No token provided for Zeptomail. You can also set the environment variable `ZEPTOMAIL_TOKEN`.'); const result = yield fetch(`https://${url}/v1.1/email`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': token, }, body: JSON.stringify({ from: { address: from.email, name: from.name }, to: to.map(({ email, name }) => ({ "email_address": { address: email, name } })), cc: cc === null || cc === void 0 ? void 0 : cc.map(({ email, name }) => ({ "email_address": { address: email, name } })), bcc: bcc === null || bcc === void 0 ? void 0 : bcc.map(({ email, name }) => ({ "email_address": { address: email, name } })), "reply_to": reply_to ? [{ address: reply_to.email, name: reply_to.name }] : undefined, subject: options.subject, textbody: text, htmlbody: html, attachments: (_c = options.attachments) === null || _c === void 0 ? void 0 : _c.map(attachment => ({ "mime_type": attachment.contentType, "name": attachment.filename, "content": encodeAttachmentToBase64(attachment.content) })), }), }); if (result.status >= 200 && result.status < 300) return; throw new Error(`Error sending email: ${result.status} ${yield result.text()}`); }); }