react-email-sender-adapters
Version:
A unified interface for sending react-email emails across multiple email services.
49 lines (48 loc) • 2.8 kB
JavaScript
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 { EmailClient } from '@azure/communication-email';
import { encodeAttachmentToBase64, parseMail } from './tools.js';
export function sendEmail(email, options) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const mail = yield parseMail(email, options);
if (!mail)
return;
const { from, to, cc, bcc, reply_to, text, html } = mail;
const connectionString = (_a = options.connectionString) !== null && _a !== void 0 ? _a : process.env.AZURE_COMMUNICATION_CONNECTION_STRING;
if (!connectionString)
throw new Error('No connection string provided for Azure Communication Services. You can set the environment variable `AZURE_COMMUNICATION_CONNECTION_STRING`.');
const client = new EmailClient(connectionString);
const poller = yield client.beginSend({
senderAddress: from.email,
headers: from.name ? { From: `"${from.name}" <${from.email}>` } : undefined,
content: {
subject: options.subject,
plainText: text,
html,
},
recipients: {
to: to.map(({ email, name }) => ({ address: email, displayName: name })),
cc: cc === null || cc === void 0 ? void 0 : cc.map(({ email, name }) => ({ address: email, displayName: name })),
bcc: bcc === null || bcc === void 0 ? void 0 : bcc.map(({ email, name }) => ({ address: email, displayName: name })),
},
replyTo: reply_to ? [{ address: reply_to.email, displayName: reply_to.name }] : undefined,
attachments: (_b = options.attachments) === null || _b === void 0 ? void 0 : _b.map(a => ({
name: a.filename,
contentType: a.contentType,
contentInBase64: encodeAttachmentToBase64(a.content),
})),
});
const response = yield poller.pollUntilDone();
if (response.error) {
throw new Error(`Failed to send email: ${response.error.code} ${response.error.message}`);
}
});
}