react-email-sender-adapters
Version:
A unified interface for sending react-email emails across multiple email services.
75 lines (74 loc) • 3.6 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 { parseMail } from './tools.js';
export function sendEmail(email, options) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d, _e;
const mail = yield parseMail(email, options);
if (!mail)
return;
const { from, to, cc, bcc, reply_to, text, html } = mail;
let { dkim } = options;
if (!dkim &&
process.env.DKIM_DOMAIN &&
process.env.DKIM_SELECTOR &&
process.env.DKIM_PRIVATE_KEY) {
dkim = {
domain: process.env.DKIM_DOMAIN,
selector: process.env.DKIM_SELECTOR,
privateKey: process.env.DKIM_PRIVATE_KEY,
};
}
const request = yield fetch('https://api.mailchannels.net/tx/v1/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
from: from,
subject: options.subject,
personalizations: [
{
to,
cc,
bcc,
reply_to,
dkim_domain: (_a = dkim === null || dkim === void 0 ? void 0 : dkim.domain) !== null && _a !== void 0 ? _a : undefined,
dkim_private_key: (_b = dkim === null || dkim === void 0 ? void 0 : dkim.privateKey) !== null && _b !== void 0 ? _b : undefined,
dkim_selector: (_c = dkim === null || dkim === void 0 ? void 0 : dkim.selector) !== null && _c !== void 0 ? _c : undefined,
},
],
content: [
{
type: 'text/plain; charset="utf-8"',
value: text,
},
...(html
? [
{
type: 'text/html; charset="utf-8"',
value: html,
},
]
: []),
...((_e = (_d = options.attachments) === null || _d === void 0 ? void 0 : _d.map(a => ({
type: `${a.contentType.replace(/[^a-z\/]/g, '')}\n` +
`Content-Transfer-Encoding: base64\n` +
`Content-Disposition: attachment; filename="${a.filename.replace(/([\\"])/g, '\\$1')}"`,
value: typeof a.content === 'string' ?
a.content :
Buffer.from(a.content).toString('base64'),
}))) !== null && _e !== void 0 ? _e : []),
],
}),
});
if (request.status !== 202) {
throw new Error(`Failed to send email: ${request.status} ${yield request.text()}`);
}
});
}