Created
December 31, 2023 23:35
-
-
Save victory-sokolov/fe5f4268996a7df81f8efef86d719db6 to your computer and use it in GitHub Desktop.
Node email send
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as nodemailer from 'nodemailer'; | |
import * as fs from 'fs'; | |
import handlebars from 'handlebars'; | |
import Mail from 'nodemailer/lib/mailer'; | |
type EmailClientArgs<TemplateData> = { | |
to: string; | |
subject: string; | |
templatePath: string; | |
templateData: TemplateData; | |
}; | |
const sendMail = async <TemplateData>(data: EmailClientArgs<TemplateData>) => { | |
const fromEmailAddress = process.env.FROM_EMAIL; | |
const smtpHost = process.env.STMP_HOST ?? ''; | |
const smtpPort = parseInt(process.env.STMP_PORT ?? '587', 10); | |
const smtpUser = process.env.STMP_USER ?? ''; | |
const smtpPassword = process.env.STMP_PASSWORD ?? ''; | |
try { | |
const smtpTransport: Mail = nodemailer.createTransport({ | |
host: smtpHost, | |
port: smtpPort, | |
auth: { | |
user: smtpUser, | |
pass: smtpPassword, | |
}, | |
}); | |
const source = fs.readFileSync(data.templatePath, { encoding: 'utf-8' }); | |
const template: HandlebarsTemplateDelegate<TemplateData> = handlebars.compile(source); | |
const html: string = template(data.templateData); | |
const updatedData: Mail.Options = { | |
to: data.to, | |
html, | |
from: `Awesome App <${fromEmailAddress}>`, | |
subject: data.subject, | |
}; | |
smtpTransport.sendMail(updatedData).then((result: nodemailer.SentMessageInfo): void => { | |
console.info(result); | |
}); | |
} catch (e) { | |
console.error(e); | |
} | |
}; | |
export { sendMail }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ConfirmEmailPayload = { | |
email: string; | |
name: string; | |
url: string; | |
}; | |
app.post('/register', async (req, res) => { | |
const { email, name } = req.body; | |
// TODO Save user into the database | |
const templateData: ConfirmEmailPayload = { | |
email, | |
name, | |
url: 'generated_confirmation_url', | |
}; | |
sendMail<ConfirmEmailPayload>({ | |
subject: 'Confirm your account', | |
templateData, | |
templatePath: path.join(__dirname, './email-template/confirm-account.html'), | |
to: email, | |
}); | |
return res.send({ message: 'User created successfully.' }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment