Files
mwitnessing/src/helpers/email.js
2024-04-05 23:44:27 +03:00

210 lines
6.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// helper module to send emails with nodemailer
const fs = require("fs");
const { MailtrapClient } = require("mailtrap");
const nodemailer = require("nodemailer");
const CON = require("./const");
const CAL = require("./calendar");
// const { google } = require("googleapis");
// const OAuth2 = google.auth.OAuth2;
const { Shift, Publisher, PrismaClient } = require("@prisma/client");
const TOKEN = process.env.TOKEN || "a7d7147a530235029d74a4c2f228e6ad";
const SENDER_EMAIL = "pw@d-popov.com";
const sender = { name: "JW Cart: Shift Info", email: SENDER_EMAIL };
const client = new MailtrapClient({ token: TOKEN });
const mailtrapTestClient = new MailtrapClient({
username: '8ec69527ff2104',//not working now
password: 'c7bc05f171c96c'
});
// ------------------ Email sending ------------------
var lastResult = null;
function setResult(result) {
lastResult = result;
}
exports.GetLastResult = function () {
return lastResult;
};
exports.SendEmail = async function (to, subject, text, html) {
const message = {
from: sender,
to,
subject,
text,
html,
};
};
exports.SendEmailHandlebars = async function (to, templateName, model) {
// Ensure the sender and mailtrapTestClient are correctly defined or imported
// Load and compile the main template
const mainTemplateSource = fs.readFileSync(path.join(__dirname, 'src', 'templates', 'emails', 'main.hbs'), 'utf8');
const mainTemplate = Handlebars.compile(mainTemplateSource);
// Dynamically load and compile the specified template
const templateSource = fs.readFileSync(path.join(__dirname, 'src', 'templates', 'emails', `${templateName}.hbs`), 'utf8');
// Extract subject and optional text version from the template source
const subjectMatch = templateSource.match(/{{!-- Subject: (.*) --}}/);
const textMatch = templateSource.match(/{{!-- Text: ([\s\S]*?) --}}/);
const subject = subjectMatch ? subjectMatch[1].trim() : 'Default Subject';
const textVersion = textMatch ? textMatch[1].trim() : null;
// Remove the subject and text annotations from the template source
const cleanTemplateSource = templateSource.replace(/{{!-- Subject: .* --}}/, '').replace(/{{!-- Text: [\s\S]*? --}}/, '');
// Compile the cleaned template
const template = Handlebars.compile(cleanTemplateSource);
// Render the specified template with the provided model
const templateHtml = template(model);
// Render the main template, inserting the specific template HTML
const html = mainTemplate({ body: templateHtml });
// Generate a plain text version if not explicitly provided
const text = textVersion || html.replace(/<[^>]*>?/gm, ''); // Simple regex to strip HTML tags. Might need refinement.
const message = {
from: sender, // Ensure 'sender' is defined
to,
subject,
text,
html,
};
// Assuming mailtrapTestClient is correctly set up to send emails
await mailtrapTestClient
.send(message)
.then(console.log)
.catch(console.error);
};
exports.SendEmail_Test = async function (to, subject, text, html) {
const message = {
from: sender,
to,
subject,
text,
html,
};
await mailtrapTestClient
.send(message)
.then(console.log, console.error, setResult);
}
// https://mailtrap.io/blog/sending-emails-with-nodemailer/
exports.SendTestEmail = async function (to) {
// await client
// .send({
// from: sender,
// to: [{ email: RECIPIENT_EMAIL }],
// subject: "Hello from Mailtrap!",
// text: "Welcome to Mailtrap Sending!",Shift Info"
// })
// .then(console.log, console.error, setResult);
// return lastResult;
const welcomeImage = fs.readFileSync(
path.join(CON.contentPath, "welcome.png")
);
await client
.send({
category: "test",
custom_variables: {
hello: "world",
year: 2022,
anticipated: true,
},
from: sender,
to: [{ email: to }],
subject: "Hello from Mailtrap!",
html: `<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body style="font-family: sans-serif;">
<div style="display: block; margin: auto; max-width: 600px;" class="main">
<h1 style="font-size: 18px; font-weight: bold; margin-top: 20px">Congrats for sending test email with Mailtrap!</h1>
<p>Inspect it using the tabs you see above and learn how this email can be improved.</p>
<img alt="Inspect with Tabs" src="cid:welcome.png" style="width: 100%;">
<p>Now send your email using our fake SMTP server and integration of your choice!</p>
<p>Good luck! Hope it works.</p>
</div>
<!-- Example of invalid for email html/css, will be detected by Mailtrap: -->
<style>
.main { background-color: white; }
a:hover { border-left-width: 1em; min-height: 2em; }
</style>
</body>
</html>`,
attachments: [
{
filename: "welcome.png",
content_id: "welcome.png",
disposition: "inline",
content: welcomeImage,
},
],
})
.then(console.log, console.error, setResult);
};
exports.SendEmail_NewShifts = async function (publisher, shifts) {
if (shifts.length == 0) return;
var date = new Date(shifts[0].startTime);
//generate ICS calendar links for all shifts
const icsLink = CAL.GenerateICS(shifts);
const shftStr = shifts
.map((s) => {
return ` ${CON.weekdaysBG[s.startTime.getDay()]
} ${CON.GetDateFormat(s.startTime)} ${s.cartEvent.location.name
} ${CON.GetTimeFormat(s.startTime)} - ${CON.GetTimeFormat(
s.endTime
)}`;
})
.join("\n");
await client.send({
from: sender,
to: [
{
email: "dobromir.popov@gmail.com",//publisher.email,
name: publisher.firstName + " " + publisher.lastName,
},
],
subject: "[CCC]: вашите смени през " + CON.monthNamesBG[date.getMonth()],
text:
"Здравейте, " + publisher.firstName + " " + publisher.lastName + "!\n\n" +
"Ти регистриран да получавате известия за нови смени на количка.\n" +
`За месец ${CON.monthNamesBG[date.getMonth()]} имате следните смени:\n` +
` ${shftStr} \n\n\n` +
"Поздрави,\n" +
"Специално Свидетелстване София",
attachments: [
{
filename: "calendar.ics",
content_id: "calendar.ics",
disposition: "inline",
content: icsLink,
},
],
})
.then(console.log, console.error, setResult);
};