@haatlabs-core/mailer
v0.10.0
Published
Send an app's email through a pluggable transport (SMTP and others).
Readme
@haatlabs-core/mailer
Sends the apps' email (sign-in codes). The apps call a Mailer; how mail leaves is an
adapter, a MailTransport, one per provider.
const mailer = mailerFromConfig(config.mail); // SMTP from config-core's MailConfig, or not configured
if (mailer.configured) await mailer.send({ to, subject, text });
createMailer({ from, transport: smtpTransport({ host, port, secure, user, password }) });
createMailer({ from, transport: memoryTransport() }); // tests: keeps what it is sentAdding a provider (an email API with a key): write an adapter, and choose it in
mailerFromConfig from the configuration. Nothing in the apps changes.
export function exampleApiTransport(options: { apiKey: string }): MailTransport {
return {
name: 'example-api',
send: async ({ from, to, subject, text }) => {
const response = await fetch('https://api.example.com/send', {
method: 'POST',
headers: { authorization: `Bearer ${options.apiKey}`, 'content-type': 'application/json' },
body: JSON.stringify({ from, to, subject, text }),
});
if (!response.ok) throw new Error(`example-api refused the email (HTTP ${response.status})`);
},
};
}An adapter throws when the provider refuses or cannot be reached, and never logs what it
sends: a sign-in code is as good as a password. Without a provider, configured is false
and send refuses with EMAIL_ERROR.
Install
pnpm add @haatlabs-core/mailer