An email sending example.
This was sent out on the Code with Hugo newsletter.
Subscribe to get the latest posts right in your inbox (before anyone else).
Example using SendGrid
On a very basic level, we want to be able to send emails.
In code terms, we want a send
function. What’s nice to have is a way to abstract the message creation, that’s a makeMailMessage
function.
See the following code:
const sgMail = require('@sendgrid/mail');
const {
SENDGRID_API_KEY,
EMAIL_OVERRIDE_TO_ADDRESS,
EMAIL_FROM_ADDRESS
} = process.env;
sgMail.setApiKey(SENDGRID_API_KEY);
function makeMailMessage ({
to,
from = EMAIL_FROM_ADDRESS,
subject,
text,
html
}) {
return {
to: EMAIL_OVERRIDE_TO_ADDRESS || to,
from,
subject,
...(html ? { html } : { text })
};
}
function send (message) {
return sgMail.send(message);
}
module.exports = {
makeMailMessage,
send
};
How do we consume this?
function doSomeSending(name, email) {
const message = makeMailMessage({
from: 'hi@codewithhugo.com',
to: email,
subject: 'Welcome to Code with Hugo',
text: `Hi ${name}, welcome to Code with Hugo.`
});
return send(message);
}
Switching to another email provider
Say we want to switch to another provider, namely Mailgun. Ideally, we don’t want to change any of the application code.
const {
MAILGUN_API_KEY,
EMAIL_DOMAIN,
EMAIL_OVERRIDE_TO_ADDRESS,
EMAIL_FROM_ADDRESS
} = process.env;
const mailgun = require('mailgun-js')({
apiKey: MAILGUN_API_KEY,
domain: EMAIL_DOMAIN
});
function makeMailMessage ({
to,
from = EMAIL_FROM_ADDRESS,
subject,
text,
html
}) {
return {
to: EMAIL_OVERRIDE_TO_ADDRESS || to,
from,
subject,
...(html ? { html } : { text })
};
}
function send (message) {
return new Promise((resolve, reject) => {
mailgun.messages().send(message, (error, body) => {
if (error) {
return reject(error);
}
resolve(body);
});
});
}
module.exports = {
makeMailMessage,
send
};
The API for our mail
module stays the same, but we’ve changed the provider under the hood 👍 .
Top comments (0)