Tuesday | 05 NOV 2024
[ previous ]
[ next ]

Nodemailer Cheatsheet

Title:
Date: 2023-03-17
Tags:  cheatsheet

Nodemailer is a mailer for nodejs and it is very easy to use.

The libraries:

pnpm install nodemailer dotenv

The code:

require("dotenv").config();

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
    host: process.env.MAIL_SERVER,
    port: process.env.MAIL_PORT,
    secure: true,
    auth: {
        user: process.env.ADMIN_EMAIL,
        pass: process.env.ADMIN_PASSWORD
    },
});

async function mailBook(book) {
    const message = {
        from: process.env.ADMIN_EMAIL,
        to: "hi@example.com",
        subject: 'Subject',
        html: "Body.",
    };
    return await transporter.sendMail(message);
}

I use dotenv to load in the .env file which contains the mailing information. You could also hardcode these in but then accidentally uploading to github becomes a danger.